答:
In my opinion, that's absolutely not how it's meant. And it's a violation of DRY.

The idea is that the entity / domain object in the middle is modeled to represent the domain as good and as convenient as possible. It is in the center of everything and everything can depend on it since the domain itself doesn't change most of the time.

If your database on the outside can store those objects directly, then mapping them to another format for the sake of separating layers is not just pointless but creating duplicates of the model and that is not the intention.

To begin with, the clean architecture was made with a different typical environment / scenario in mind. Business server applications with behemoth outer layers that need their own types of special objects. For example databases that produce SQLRow objects and need SQLTransactions in return to update items. If you were to use those in the center, you were to violate the dependency direction because your core would depend on the database.

With lightweight ORMs that load and store entity objects thats not the case. They do the mapping between their internal SQLRow and your domain. Even if you need put an @Entitiy annotation of the ORM into your domain object, I'd argue that this does not establish a "mention" of the outer layer. Because annotations are just metadata, no code that isn't specifically looking for them will see them. And more importantly, nothing needs to change if you remove them or replace them with a different database's annotation.

In contrast, if you do change your domain and you made all those mappers, you have to change a lot.

Amendment: Above is a little oversimplified and could even be wrong. Because there is a part in clean architecture that wants you to create a representation per layer. But that has to be seen in context of the application.

Namely the following here https://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html

The important thing is that isolated, simple, data structures are passed across the boundaries. We don’t want to cheat and pass Entities or Database rows. We don’t want the data structures to have any kind of dependency that violates The Dependency Rule.

Passing entities from the center towards the outer layers does not violate the dependency rule, yet they are mentioned. But this has a reason in the context of the envisioned application. Passing entities around would move the application logic towards the outside. Outer layers would need to know how to interpret the inner objects, they would effectively have to do what inner layers like the "use case" layer is supposed to do.

Besides that, it also decouples layers so that changes to the core don't necessarily require changes in outer layers (see SteveCallender's comment). In that context, it's easy to see how objects should represent specifically the purpose they are used for. Also that layers should talk to each other in terms of objects that are made specifically for the purpose of this communication. This can even mean that there are 3 representations, 1 in each layer, 1 for transport between layers.

And there is https://blog.8thlight.com/uncle-bob/2011/11/22/Clean-Architecture.html which addresses above:

Other folks have worried that the net result of my advice would be lots of duplicated code, and lots of rote copying of data from one data structure to another across the layers of the system. Certainly I don’t want this either; and nothing I have suggested would inevitably lead to repetition of data structures and an inordinate of field copying.

That IMO implies that plain 1:1 copying of objects is a smell in the architecture because you're not actually using the proper layers and /or abstractions.

He later explains how he imagines all the "copying"

You separate the UI from the business rules by passing simple data structures between the two. You don’t let your controllers know anything about the business rules. Instead, the controllers unpack the HttpRequest object into a simple vanilla data structure, and then pass that data structure to an interactor object that implements the use case by invoking business objects. The interactor then gathers the response data into another vanilla data structure and passes it back to the UI. The views do not know about the business objects. They just look in that data structure and present the response.

In this application, there is a big difference between the representations. The data that flows isn't just the entities. And this warrants and demands different classes.

However, applied to a simple Android application like a photo viewer where the Photo entity has about 0 business rules and the "use case" that deals with them is nearly non-existing and is actually more concerned about caching & downloading (that process should IMO be represented more explicitly), the point to make separate representations of a photo starts to vanish. I even get the feeling that the photo itself is the data transfer object while the real business-logic-core-layer is missing.

There is a difference between "separate the UI from the business rules by passing simple data structures between the two" and "when you want to display a photo rename it 3 times on the way".

Besides that, the point where I see those demo applications fail at representing the clean architecture is that they add huge emphasis on separating layers for the sake of separating layers but effectively hide what the application does. That is in contrast to what is said in https://blog.8thlight.com/uncle-bob/2011/09/30/Screaming-Architecture.html - namely that

the architecture of a software application scream about the use cases of the application

I don't see that emphasis on separating layers in the clean architecture. It's about dependency direction and focusing on representing the core of the application - entities and use cases - in ideally plain java without dependencies towards the outside. It's not so much about dependencies towards that core.

So if your application actually has a core that represents business rules and use cases, and / or different people work on different layers, please separate them in the intended way. If you're on the other hand just writing a simple app all by yourself don't overdo it. 2 layers with fluent bounds may be more than enough. And layers can be added later on as well.

Title: Uncle Bob's clean architecture - An entity/model class for each layer?

Body:
BACKGROUND :

I'm trying to use Uncle Bob's clean architecture in my android app. I studied many open source projects that are trying to show the right way to do it, and I found an interesting implementation based on RxAndroid.

WHAT I NOTICIED :

In every layer (presentation, domain and data), there's a model class for the same entity (talking UML). Plus, there are mapper classes that take care of object's transformation whenever the data is crossing the boundaries (from layer to another).

QUESTION :

Is it required to have model classes in every layer when I know that they'll all end up with the same attributes if all CRUD operations are needed? Or, is it a rule or a best practice when using the clean architecture?

OwnerDisplayName: zapl


问:
Would UTF-8 be able to support the inclusion of a vast alien language with millions of new characters?
In the event an alien invasion occurred and we were forced to support their languages in all of our existing computer systems, is UTF-8 designed in a way to allow for their possibly vast amount of characters?

(Of course, we do not know if aliens actually have languages, if or how they communicate, but for the sake of the argument, please just imagine they do.)

For instance, if their language consisted of millions of newfound glyphs, symbols, and/or combining characters, could UTF-8 theoretically be expanded in a non-breaking way to include these new glyphs and still support all existing software?

I'm more interested in if the glyphs far outgrew the current size limitations and required more bytes to represent a single glyph. In the event UTF-8 could not be expanded, does that prove that the single advantage over UTF-32 is simply size of lower characters?

答:
Edit: The question now says "millions of new characters". This makes it easy to answer:

No. Utf-8 is a Unicode encoding. Unicode have a codespace which allows 1,114,112 distinct codepoints, and less than a million is currently unassigned. So it is not possible to support millions of new characters in Unicode. By definition no Unicode encoding can support more characters than what is defined by Unicode. (Of course you can cheat by encoding a level further - any kind of data can be represented by just two characters after all.)

To answer the original question:

Unicode does not support languages as such, it supports characters - symbols used to represent language in written form.

Not all human languages have a written representation, so not all human languages can be supported by Unicode. Furthermore many animals communicate but don't have a written language. Whales for example have a form of communication which is complex enough to call a language, but does not have any written form (and cannot be captured by existing phonetic notation either). So not even all languages on earth can be supported by Unicode.

Even worse is something like the language of bees. Not only does it not have a written form, it cannot meaningfully be represented in written form. The language is a kind of dance which basically points in a direction but relies on the current position of the sun. Therefore the dance only have informational value at the particular place and time where it is performed. A symbolic or textual representation would have to include information (location, position of the sun) which the language of bees currently cannot express.

Even a written or symbolic form of communication might not be possible to represent in Unicode. For example illustrations or wordless comics cannot be supported by Unicode since the set of glyphs is not finite. You will notice a lot of pictorial communication in international settings like an airport, so it is not inconceivable that a race of space-travelling aliens will have evolved to use a pictorial language.

Even if an alien race had a language with a writing system with a finite set of symbols, this system might not be possible to support in Unicode. Unicode expects writing to be a linear sequence of symbols. Music notation is an example of a writing system which cannot be fully represented in Unicode, because meaning is encoded in both choice of symbols and vertical and horizontal placement. (Unicode does support individual musical symbols, but cannot encode a score.) An alien race which communicated using polyphonic music (not uncommon) or a channel of communication of similar complexity, might very well have a writing system looking like an orchestral score, and Unicode cannot support this.

But lets for the sake of argument assume that all languages, even alien languages, can be expressed as a linear sequence of symbols selected from a finite set. Is Unicode big enough for an alien invasion? Unicode have currently less than a million unassigned codepoints. The Chinese language contains a hundred thousands characters according to the most comprehensive Chinese dictionary (not all of them are currently supported by Unicode as distinct characters). So only ten languages with the complexity of Chinese would use up all of Unicode. On earth we have hundreds of distinct writing systems, but luckily most are alphabetical rather than ideographical and therefore contains a small number of character. If all written languages used ideograms like Chinese, Unicode would not even be big enough for earth. The use of alphabets is derived from speech which only uses a limited number of phonemes, but that is particular for human physiology. So even a single alien planet with only a dozen of ideographical writing systems might exceed what Unicode can support. Now consider if that this alien already have invaded other planets before earth and included their writing systems in the set of characters which have to be supported.

Expansion or modification of current encodings, or introduction of new encodings will not solve this, since the limitation is in the number of code points supported by Unicode.

So the answer is most likely no.

ContentLicense: CC BY-SA 3.0


问:
Continuous Deployment with gitignore
When doing continuous deployment with Git, how do you handle ignored files in gitignore?  Those files are ignored for privacy reasons (i.e. don't want them pushed out to other remote repositories, like GitHub), but with those ignored files not being pushed to the continuous deployment repository, they application would not run (as the ignored files are required for the software to function correctly).

How do people typically go about this?  In this case, is Git not the best candidate for continuous deployment due to ignored files?

答:
If your software does not run without those files, you will have a problem with any kind of deployment, manual, automatic or continuous, with any kind of VCS, or even without any VCS. So either change your software so that it can run actually without those files (for example, it could assume some kind of "default parameters" if the files are missing), or you provide some version of those file suitable for deployment which are copied (as part of the deployment step) to the destination environment in case there is no "private" version of those files in place.

If you are talking about something like a file containing database credentials to logon to the server, which, for security reasons, you do not want to be in version control, then you will have to put that file into the deployment environment once, probably manually, by a person which has enough rights or knows the password. But that is intentional and should not stop you from deploying daily new versions of your software. Just make sure a credentials files in place is not overwritten when you deploy a new version.

Title: Continuous Deployment with gitignore


问:
What is the purpose of wrapped values in Haskell?
I've recently read an article about Functors, Applicatives and Monads in Haskell and it concludes with these statements:

functors: you apply a function to a wrapped value using fmap or <$>

applicatives: you apply a wrapped function to a wrapped value using <*> or liftA

monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM

This is all clear but I don't get what the purpose of the a wrapped value is. Do they work like the decorators in python or the Optional in java? I would greatly appreciate some practical example from the real world.

答:
Java's Optional is essentially equivalent to Haskell's Maybe monad, so that's a good starting place for understanding how these "wrapped values" behave.

Functors, Applicatives and Monads are ways of modelling some kind of additional behavior that can modify an existing type. Maybe takes a type, and modifies it so that it can model both a one single instance or no instance of that type. List modifies a type so that it models a sequence of instances of the given type.

Each of these typeclasses provides a way to apply a given function to the wrapped type, respecting the modifications that the wrapping type makes. For example, in Haskell,

Functors

Functors use the fmap or <$> functions (different names for the same thing):

fmap or <$> Functor f => (a -> b) -> f a -> f b

This takes a function and applies to to the wrapped elements

```<code>fmap (\x -> x + 1) (Just 1)   -- Applies (+1) to the inner value, returning (Just 2)
fmap (\x -> x + 1) Nothing    -- Applies (+1) to an empty wrapper, returning Nothing

fmap (\x -> x + 1) [1, 2, 3]  -- Applies (+1) to all inner values, returning [2, 3, 4]
(\x -> x + 1) <$> [1, 2, 3]   -- Same as above
</code>```

Applicatives

Applicatives use the <*> function:

<*> Applicative f => f (a -> b) -> f a -> f b

This takes a wrapped function and applies it to the wrapped elements

```<code>(Just (\x -> x + 1)) <*> (Just 1) -- Returns (Just 2)
(Just (\x -> x + 1)) <*> Nothing  -- Returns Nothing
Nothing <*> (Just 1)              -- Returns Nothing
[(*2), (*4)] <*> [1, 2]           -- Returns [2, 4, 4, 8]
</code>```

Monads

There are two relevant functions in the Monad typeclass:

return Monad m => a -> m a

(>>=) Monad m => m a -> (a -> m b) -> m b (pronounced "bind")

The return function bears no resemblance to the one you may be familiar with in C-style languages. It takes a raw, unwrapped value, and wraps it up in the desired monadic type.

```<code>makeJust :: a -> Maybe a
makeJust x = return x

let foo = makeJust 10 -- returns (Just 10)
</code>```

The bind function lets you temporarily unwrap the inner elements of a Monad and pass them to a function that performs some action that wraps them back UP in the same monad. This can be used with the return function in trivial cases:

```<code>[1, 2, 3, 4] >>= (\x -> return (x + 1))  -- Returns [2, 3, 4, 5]
(Just 1) >>= (\x -> return (x + 1))      -- Returns (Just 2)
Nothing >>= (\x -> return (x + 1))       -- Returns Nothing
</code>```

Where it gets interesting is when you have functions to chain together that don't require you to use return. I like to use getLine and putStrLn as examples, which have the following signatures using the IO monad:

getLine IO String

putStrLn String -> IO ()

You can call these functions like so:

```<code>getLine >>= (\x -> putStrLn x) -- Gets a line from IO and prints it to the console
getLine >>= putStrLn -- With currying, this is the same as above
</code>```

You could also use the >>= function to chain a few operations together.

```<code>-- Reads a line from IO, converts to a number, adds 10 and prints it
getLine >>= (return . read) >>= (return . (+10)) >>= putStrLn . show
</code>```

Body:
Java's Optional is essentially equivalent to Haskell's Maybe monad, so that's a good starting place for understanding how these "wrapped values" behave.

Functors, Applicatives and Monads are ways of modelling some kind of additional behavior that can modify an existing type. Maybe takes a type, and modifies it so that it can model both a one single instance or no instance of that type. List modifies a type so that it models a sequence of instances of the given type.

Each of these typeclasses provides a way to apply a given function to the wrapped type, respecting the modifications that the wrapping type makes. For example, in Haskell,

Functors

Functors use the fmap or <$> functions (different names for the same thing):

fmap or <$> Functor f => (a -> b) -> f a -> f b

This takes a function and applies to to the wrapped elements

fmap (\x -> x + 1) (Just 1)   -- Applies (+1) to the inner value, returning (Just 2)
fmap (\x -> x + 1) Nothing    -- Applies (+1) to an empty wrapper, returning Nothing

fmap (\x -> x + 1) [1, 2, 3]  -- Applies (+1) to all inner values, returning [2, 3, 4]
(\x -> x + 1) <$> [1, 2, 3]   -- Same as above

Applicatives

Applicatives use the <*> function:

<*> Applicative f => f (a -> b) -> f a -> f b

This takes a wrapped function and applies it to the wrapped elements

(Just (\x -> x + 1)) <*> (Just 1) -- Returns (Just 2)
(Just (\x -> x + 1)) <*> Nothing  -- Returns Nothing
Nothing <*> (Just 1)              -- Returns Nothing
[(*2), (*4)] <*> [1, 2]           -- Returns [2, 4, 4, 8]

Monads

There are two relevant functions in the Monad typeclass:

return Monad m => a -> m a

(>>=) Monad m => m a -> (a -> m b) -> m b (pronounced "bind")

The return function bears no resemblance to the one you may be familiar with in C-style languages. It takes a raw, unwrapped value, and wraps it up in the desired monadic type.

makeJust :: a -> Maybe a
makeJust x = return x

let foo = makeJust 10 -- returns (Just 10)

The bind function lets you temporarily unwrap the inner elements of a Monad and pass them to a function that performs some action that wraps them back UP in the same monad. This can be used with the return function in trivial cases:

[1, 2, 3, 4] >>= (\x -> return (x + 1))  -- Returns [2, 3, 4, 5]
(Just 1) >>= (\x -> return (x + 1))      -- Returns (Just 2)
Nothing >>= (\x -> return (x + 1))       -- Returns Nothing

Where it gets interesting is when you have functions to chain together that don't require you to use return. I like to use getLine and putStrLn as examples, which have the following signatures using the IO monad:

getLine IO String

putStrLn String -> IO ()

You can call these functions like so:

getLine >>= (\x -> putStrLn x) -- Gets a line from IO and prints it to the console
getLine >>= putStrLn -- With currying, this is the same as above

You could also use the >>= function to chain a few operations together.

-- Reads a line from IO, converts to a number, adds 10 and prints it
getLine >>= (return . read) >>= (return . (+10)) >>= putStrLn . show


问:
Best Practices for MVC Architecture
My question is more about how to architect an MVC application.  For example, we are encouraged to use DI with the Repository pattern to decouple data access from the controller, however very little is said on HOW to do that specifically for MVC.  Where would we place the Repository classes, for instance?  They don't seem to be model related specifically, since the model should likewise be relatively decoupled from the actual data access technologies.

A second question involves how to structure the layers or tiers.  Most example applications (Nerd dinner, Music Store, etc..) all seem to use a single tier, 2 layer approach (not counting tests) that typically has controllers directly calling L2S or EF code.

If I want to create a multi-tier/layer application what are some of the best practices there in regards to MVC?

答:
DI is accomplished in ASP MVC using a Controller Factory. This factory is used to resolve your controller dependencies.

MvcContrib has some Controller Facotry implementations that you can use out of the box. I use their Castle Windsor implementation and it works well. Would also suggest checking out their TestHelper Class. It has some very cool functionality for mocking Controller HTTPContext, Sessions, etc..
MVCContrib

Personally I like to give my Models a Repository instance to work with. The model exposes an api to the repository (CRUD). The controller's dependency on a particular model is injected on creation (constructor) this is injected via the Controller Factory. This is my entry point to the object graph which my IoC container manages.

OwnerDisplayName: Mystere Man

Title: Best Practices for MVC Architecture

OwnerDisplayName: Nick


答:
Well Optional is a monad (and therfore an applicative functor and a functor), and indeed many container types are monadic as well, and people usually have a fairly good intuition for how containery type things work as these things, as I believe you do from your question.

However lots of things that aren't normally thought of as containers can also be monads, applicative or functors e.g. parsers combinators or IO or writing to a log. An alternative way of looking at them is as computations in some context, for instance, while List is obviously a container of values you can also consider computations in the List monad as representing nondeterministic computations

What I'm leading up to here is that monads are intrinsictly more abstract than the examples you are after. they are literally:

a type constructor

a return/unit function

and a bind (or join and fmap) function

that satisfy the 3 monad laws, there is no further unifying principle than that (for a monad, replace with relevant functions and laws for Applicative and Functor)

Title: What is the purpose of wrapped values in Haskell?

Body:
I've recently read an article about Functors, Applicatives and Monads in Haskell and it concludes with these statements:

functors: you apply a function to a wrapped value using fmap or <$>

applicatives: you apply a wrapped function to a wrapped value using <*> or liftA

monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM

This is all clear but I don't get what the purpose of the a wrapped value is. Do they work like the decorators in python or the Optional in java? I would greatly appreciate some practical example from the real world.


答:
That article has the virtue of being very visual and intuitive... but at the cost of building intuitions that are often false.  The concepts of functor, applicative and monad do not require you to have "wrapped" values, strictly speaking.

One good example to consider here is the concept of promises that's been gaining traction recently (particularly in Javascript).  A promise, in this sense, is an object that acts as a placeholder for the result value of an asynchronous, background computation, like fetching some data from a remote service.  In addition to that, it serves as a mediator between the asynchronous computation and functions that need to operate on its anticipated result.

Promise libraries usually support a functorial/monadic API where you can "chain" a function onto a promise, which produces another promise that produces the result of applying that function to the original promise's result.

This provides a vivid example of the value of the functor/monad interface, because the whole point of promises is that they allow you to say what function should apply to the result of a background task, before that task has completed.  When you map a function over a promise, the value that your function should apply to may not have been computed yet (and in fact, if there is an error somewhere it may never be computed).

More generally, you can think of functor/applicative/monad as interfaces for mediator objects that sit in between functions and arguments, and connect them indirectly according to some policy.  The simplest way to use a function is just to call it with some arguments; but if you have first-class functions, you have other, indirect options—you can supply the function to a mediator object that will control if, when and how many times the function will be called, and what to do with its result.  Promises are one such example:

They call the functions supplied to them when the result of some background task is completed

The results of those functions are then handed over to other promises that are waiting for them.


答:
Another option is to store the sensitive information inside of your deployment tool. And the deployment tool configuration in a separate private source repository.

Leaving the sensitive data on the target machine works, but might bit-rot - someone changes it not following procedures, the machine brakes and no one remembers the correct settings, etc...

Saltstack for example has
https://docs.saltstack.com/en/latest/topics/pillar/index.html

Title: Continuous Deployment with gitignore

Body:
When doing continuous deployment with Git, how do you handle ignored files in gitignore?  Those files are ignored for privacy reasons (i.e. don't want them pushed out to other remote repositories, like GitHub), but with those ignored files not being pushed to the continuous deployment repository, they application would not run (as the ignored files are required for the software to function correctly).

How do people typically go about this?  In this case, is Git not the best candidate for continuous deployment due to ignored files?


答:
Really, only 2 Unicode code-points code stand for infinitely many glyphs, if they were combining characters.

Compare, for example, the two ways that Unicode encodes for the Korean Hangul alphabet: Hangul Syllables and Hangul Jamo. The character 웃 in Hangul Syllabels is the single code-point C6C3 whereas in Hangul Jamo it is the three code-points 110B (ㅇ) 116E (ㅜ) 11B9 (ㅅ). Obviously, using combining characters takes up vastly fewer code-points, but is less efficient for writing because more bytes are needed to write each character.

With this trick, there is no need to go beyond the number of code-points that can currently be encoded in UTF-8 or UTF-16.

I guess it comes down to how offended the aliens would be if their language happened to require many more bytes per message than earthly languages. If they don't mind, say, representing each of their millions of characters using a jumble of say, 100k combining characters, then there's no problem; on the other hand if being forced to use more bytes than earthlings makes them feel like second-class citizens, we could be in for some conflict (not unlike what we already observe with UTF-8).

Title: Would UTF-8 be able to support the inclusion of a vast alien language with millions of new characters?

Body:
In the event an alien invasion occurred and we were forced to support their languages in all of our existing computer systems, is UTF-8 designed in a way to allow for their possibly vast amount of characters?

(Of course, we do not know if aliens actually have languages, if or how they communicate, but for the sake of the argument, please just imagine they do.)

For instance, if their language consisted of millions of newfound glyphs, symbols, and/or combining characters, could UTF-8 theoretically be expanded in a non-breaking way to include these new glyphs and still support all existing software?

I'm more interested in if the glyphs far outgrew the current size limitations and required more bytes to represent a single glyph. In the event UTF-8 could not be expanded, does that prove that the single advantage over UTF-32 is simply size of lower characters?


问:
What is a good security practice for storing a critical database on developer's laptops?
We have a few givens:

Developers need a replica of the production database on their machines.

Developers have the password to said database in the App.config files.

We don't want the data in said database compromised.

A few suggested solutions and their drawbacks:

Full-disk-encryption. This solves all problems, but degrades the laptop's performance, and we are a start-up, so don't have money for powerhorses.

Creating a VM with encrypted hard disk, and store the database on it. It works well, but it doesn't help too much, since there's a password in Web.Config.

Solution number 2 + requiring the developer to type the database password every time he runs anything. It solves all problems, but it is really cumbersome for developers that sometimes fire up the application multiple times a minute. Also, we have multiple applications that connect to the same database, and implementation of a password screen will have to differ in each.

So, my question is, if there's any common solution to such problem, or any suggestions on how to make any of the above solutions workable?

答: One possible option is to make a copy of the database and scrub that copy with a script so you end up with different data than what is actually in production. You won't end up with the same data as production But you will have the same scale.</p>


答:
You don't state which database and which environment.

If you can use integrated security then the database is not accessible without logged in as that user.  Yes if the data is on the hard disc it can be hacked but this is a first level defense.

App.config makes my think this may be a .NET.  Put config in a thumb drive and read it from the thumb drive.  If the drive is not present then make the user type in the password.

Is there a way to store the password in memory the first time it is entered and read by all.  Again you don't state the environment.   Memory-Mapped Files

With some TDE you can store the key on a separate device so they just supply the key when the database sever is started.

Title: What is a good security practice for storing a critical database on developer's laptops?

Body:
We have a few givens:

Developers need a replica of the production database on their machines.

Developers have the password to said database in the App.config files.

We don't want the data in said database compromised.

A few suggested solutions and their drawbacks:

Full-disk-encryption. This solves all problems, but degrades the laptop's performance, and we are a start-up, so don't have money for powerhorses.

Creating a VM with encrypted hard disk, and store the database on it. It works well, but it doesn't help too much, since there's a password in Web.Config.

Solution number 2 + requiring the developer to type the database password every time he runs anything. It solves all problems, but it is really cumbersome for developers that sometimes fire up the application multiple times a minute. Also, we have multiple applications that connect to the same database, and implementation of a password screen will have to differ in each.

So, my question is, if there's any common solution to such problem, or any suggestions on how to make any of the above solutions workable?


答:
Where would we place the Repository classes, for instance?

They belong in the model; they're the in-application model.

How to do I structure the layers? If I want to create a multi-tier/layer application what are some of the best practices there in regards to MVC?

Tiers Represent physical separations of code. Layers represent logical separations. The layers (as they presently are) work well for MVC. Depending on the amount of business logic, it can either be placed in your Controller, or it can be placed in a separate assembly and can be used by the controller during the request cycle.

Title: Best Practices for MVC Architecture

Body:
My question is more about how to architect an MVC application.  For example, we are encouraged to use DI with the Repository pattern to decouple data access from the controller, however very little is said on HOW to do that specifically for MVC.  Where would we place the Repository classes, for instance?  They don't seem to be model related specifically, since the model should likewise be relatively decoupled from the actual data access technologies.

A second question involves how to structure the layers or tiers.  Most example applications (Nerd dinner, Music Store, etc..) all seem to use a single tier, 2 layer approach (not counting tests) that typically has controllers directly calling L2S or EF code.

If I want to create a multi-tier/layer application what are some of the best practices there in regards to MVC?

OwnerDisplayName: George Stocker

ContentLicense: CC BY-SA 2.5


问:
What data structure can I use to implement a double ended priority queue with log(n) insertion and find?
How can I implement a double ended priority queue with O(log(n)) complexity of insertion, find min and find max operations?

I was thinking of using a red black tree, but it is a little bit complicated. Is there a simpler alternative?

I have also heard of a double ended heap, but the complexity of finding or deleting the min and max seems to be be linear and not logarithmic.

答:
Here is what I did for a block allocator free-list implementation that needed a double-ended priority queue:

Use standard red-black tree algorithms, with one small enhancement:

During insertion keep track of the minimum and maximum element in the tree as you do insertions or deletions. This only adds at most O(log n) comparisons as overhead during the already O(log n) insertion process, so doesn't change the overall algorithmic complexity.

This yields:

O(log n): insertion

O(1): find-min and delete-min

O(1): find-max and delete-max

Since those were the only operations I needed for my particular application, this was pretty much the best possible data structure. Even if you needed other priority queue operations (like changing priorities, etc) pretty much everything is still going to be O(log n) worst case because of the red-black tree.

The reason you get O(1) for both find-min/max as well as delete-min/max is that you've kept track of the minimum and maximum element during insertion, so you can immediately find it, eliminating the O(log n) for the search. Then the red-black tree algorithm guarantees O(1) operations to rebalance the tree after the element is removed. (This is a well known and very important property of red-black trees. This wouldn't be the case with most other binary search trees, such as AVL trees, which require O(log n) operations during rebalancing.)


问:
To find the oldest/newest element in a heap
I want to find the oldest/newest element added into a heap of size k. At any given point of time if I have to find say the oldest element in the heap is there any approach with O(1) space and O(1) time.

I was thinking of an approach of having a queue of the same size as that of the heap and add all the element into the queue as they are added to the heap. This yields a constant time solution but this requires an extra O(k) space. I would like to know if this problem can be solved with constant space.

答:
I've copied my answer from this question: What data structure can I use to implement a double ended priority queue with log(n) insertion and find? I've repeated it here because these questions don't really appear to be duplications, but simply two questions that can be -- but don't have to be -- solved with the same technique:

Here is what I did for a block allocator free-list implementation that needed a double-ended priority queue:

Use standard red-black tree algorithms, with one small enhancement:

During insertion keep track of the minimum and maximum element in the tree as you do insertions or deletions. This only adds at most O(log n) comparisons as overhead during the already O(log n) insertion process, so doesn't change the overall algorithmic complexity.

This yields:

O(log n): insertion

O(1): find-min and delete-min

O(1): find-max and delete-max

Since those were the only operations I needed for my particular application, this was pretty much the best possible data structure. Even if you needed other priority queue operations (like changing priorities, etc) pretty much everything is still going to be O(log n) worst case because of the red-black tree.

The reason you get O(1) for both find-min/max as well as delete-min/max is that you've kept track of the minimum and maximum element during insertion, so you can immediately find it, eliminating the O(log n) for the search. Then the red-black tree algorithm guarantees O(1) operations to rebalance the tree after the element is removed. (This is a well known and very important property of red-black trees. This wouldn't be the case with most other binary search trees, such as AVL trees, which require O(log n) operations during rebalancing.)


问:
Few concerns regarding SDLC phases and SRS
I am working in small IT industry and we are trying to implement processes and SDLC into our organization, since we are in initial phase I have few concerns and so want some consultant from experts here:

Currently we create 1 major SDLC documents: SRS.

SRS is initially created by our business development executives who are the first POC with client whenever any requirement comes in. They create a rough SRS document with all the requirements from client.

Once the requirements are freezed, SRS is passed on to the Project Manager who then furnishes the document as per the requirements specified by business development executives.

My concerns:

Is this the correct way we are following, if not please suggest the correct way.

Should SRS be prepared only after requirements are freezed ?

If yes then which document should be prepared by business development executives which they are still gathering requirement from clients.

答:
I don't like that your requirements appear to live in a Software Requirements Specification document instead of a requirements management tool. A document-based approach makes it more difficult to capture traceability between requirements and to reuse requirements across projects or products in a software product line. These may not necessarily be concerns for you right now, but it would be easier to start with a requirements management tool than try to manage documents and then import several documents into a tool and remove duplication and manage traceability after the fact.

Perhaps it's implied, but the process that you describe doesn't have any kind of iteration on the requirements. When the initial customer requirements come in from the business development executives, they probably won't be suitable for performing design, implementation, and test activities. At least some of the requirements will need to be clarified and rewritten. In addition, there will likely be other requirements that come from other sources - your test team may introduce testability requirements that you need to implement, there may be business or regulatory requirements that impact your product. These will also need to be captured in the SRS and reviewed with the customer to ensure they understand and can live with those requirements.

The concept of freezing an SRS is a little strange to me. Even in a sequential process, the client may want to change the requirements. There is a cost and schedule impact associated with a requirements change (especially late in a sequential process), but the process for receiving a change request, evaluating the request, and determining a response and disposition should probably be something that you want to define.

If you would like further guidance on working with software requirements and developing an approach, I would highly recommend getting a copy of Software Requirements (3rd Edition) by Karl Wiegers and Joy Beatty. A copy of IEEE Standard 29148-2011 may also be useful.

OwnerDisplayName: pratik

OwnerDisplayName: Thomas Owens


问:
How to integrate modified generated code into the build process?
I'm using a code generator which has the following workflow:

Configure stuff

Generate code

Modify generated code with user code at specifically annotated positions.

If changes are required to the configuration, the user code will remain after generating the code again because the annotated positions are untouched by the code generator.

My problem is, how do I properly put this into version control and into a build process?

Idea 1

Put configuration and generated code with user changes into version control. This is the easiest to integrate with the current build tools. However, the configuration and generated code might diverge. To mitigate that, the build process might generate the code again and verify that it's the same as the committed code.

Idea 2

Put just configuration and user changes into version control. This way, no generated files are stored in version control. The user code should then somehow be developed separately and automatically integrated into the generated code later.

For the curious, the code generator is Dave 2, although it's not really relevant for the question.

In my opinion, this question is ontopic, because it is about using a Tool in a Software Development Workflow.

答:
Fully observing the Don't Repeat Yourself principle would mean that you shouldn't store any information twice in your repository. If you auto-generate source code (or any kind of file, really) and then tweak it further, the only way to fully comply is to store the templates that drive the generator, plus a diff between its output and the actual files you want.

But DRY is not a cosmic law. It is an idea that experience has show to have a lot of merit in many cases. Whether or not it has merit in your case depends on the particulars of your code base. Do you often re-run the generator? Is the output huge? Is there a lot of danger that you might forget to re-apply one of the tweaks in a future iteration? Those are the kind of questions you need answered to decide whether to be fully DRY, or whether to break that principle deliberately, knowing that its cons outweight its pros in this case.


问:
how to evaluate own project
I am working on a open source project in pure C, that I have started some time ago, but only recently found time to add some features. I can clearly some weaknesses of my old design, so I am trying to refactor my old code. I have no idea however, how to evaluate properly my new code. Do you know about any techniques or tools for code evaluation? I am pretty good with object oriented design, but for about three years I had no contact with purely structural one. Therefore I don't have enough experience, to be able to discern between good and bad design choices.

答:
The question is so general, that the answers will either concern one point (as "don't copy-paste code", "one method must do one and one only thing", "comment your code properly", etc.), or be also too general, like mine:

There are two ways to evaluate your own project.

The first one is obviously to give this project to a more experienced developer, and to count the number of WTFs during review.

(source)

The problem with this approach that it is more the developer is experienced, better will be the review, but you will receive more criticism from a more experienced developer, so it may be really discouraging and depressing. On the other hand, if you choose a developer which does not want to criticize you too much or is not very experienced, their review may not be too useful.

The second way is to wait when you will acquire more experience, then review your own project, thus optimizing, refactoring and modifying the code.

You can then determine a lifespan of your code, and try to review it regularly. For example, in my case, the lifespan is one year: it means that I may modify the code which I wrote six months ago, but if the code was written two years ago, it has a strong chance of being thrown, then rewritten completely, since it just sucks too much.

To resume, there are no ways to really evaluate your own code. It is perfect for you at the moment when you write it. But the same code is bad when reviewed by a more experienced developer, and this same code will be bad when you will review it after learning and understanding new things.

In other words, there is no objective way to evaluate the quality of code: you can only evaluate the quality of code (and so your skills) relatively to the code of other developers (and yourself after learning more things).

OwnerDisplayName: gruszczy

Title: how to evaluate own project


问:
Non-fixed-size Fenwick Tree implementation
I'm planning to implement a non-fixed-size Fenwick tree. That is, a Fenwick tree that allows interleaving range queries with adding/removing elements.

All implementations and samples I've seen so far are for fixed-size Fenwick trees, where the number of elements is known before preprocessing the frequencies. They use a fixed size array, so it's not possible to add or remove elements after preprocessing is done. (Well, it is possible, but I'd need to re-build the structure).

I thought of extending TreeMap or maybe AbstractMap, but as TreeMap is actually a red-black tree, I don't know how to implement the red-black mechanics (so that the tree remains balanced) without loosing the cumulative sums of nodes involved in the rebalancing process.

So I thought that maybe I should take another approach: why not extend or adapt a simple random access ArrayList and re-calculate all cumulative sums when the underlying array is resized? This would of course have an impact but, hey, that's exactly what a HashMapdoes.

This is why I wanted to ask here first, in case someone has already done it, and to check which approach you think is the best.

答:
The Fenwick Tree is a space-efficient data structure because it foregoes the original data and instead only stored some "encoded" version.

As you have noticed, however, this encoding means that you cannot add or remove an element (except at the tail) without a lot of churn.

If your add/remove operations are infrequent enough than rebuilding the whole underlying array is possible in your case; just do so. This will mean a latency spike, but should not affect throughput significantly.

If, on the other hand, this overhead is not acceptable, then the Fenwick Tree is just not an appropriate data-structure for your issue. In this case, I would recommend an Augmented Binary Search Tree.

Take the Binary Search Tree implementation that you prefer (Red-Black Tree, AVL Tree, Splay Tree, ...) or even a B-Tree if you'd like, and augment the information each node/element carries with:

the number of left and right children

the sum of left and right children

When adding/removing elements you will need to keep the numbers and sums up-to-date on the path leading to the root. Adding and removing is O(log N) already, so since you'll be updating O(log N) nodes/elements you will not change the complexity significantly.

Then, implement new methods to access by index and retrieve the sum. Note that the index is not immediately accessible, but knowing the left sub-tree has 4 nodes, if you wish to access:

index 2, then you should go the left sub-tree

index 5, then you are here

index 7, then you should go the right sub-tree (and access index 2 in the right sub-tree: 7 - sizeof(left sub-tree) - 1)


问:
Is Functional Programming possible in Java?
I was browsing through the Amazon.com Bookstore and I came across the book "Functional Programming for Java Developers".

I know some very basic Functional Programming and have been programming in Java for 3 years.

I would like to know is Functional Programming even possible in Java?

答:
It may seems possible but it will not be a pure functional programming. It may results to imperative programming.

There is no asking why he mean by possible functional programming as mentioned by haylem. Here it is:

It depends what you mean by "functional programming" and by
  "possible".

Functional programming cannot have different definitions or meaning though it may have many explanations.

Like OOP, can we ask "what do you mean by OOP?".

Definitely there will be lot of explanations but it will just pertain to one objective, the objective of OOP.

The same applies to functional programming.

When we say functional meaning the programs consist of functions.

The role of the functions is to return an evaluated argument/parameter (argument is variable is the expression came when calling the function while parameter is variable that is a part of the function declaration).

Also functions will always return the same result when same arguments is passed. In that way it is easier to avoid bugs or debug future bugs. By functional programming we can avoid side effects like modifying global variable.

example in JavaScript:

function increment(lis){
    return lis.map(
        function (x){
            return x+2;
        }
    );
}

var myList = [4, 7, 2, 3];
console.log(increment(myList));
console.log(myList);
```

The function increment adds 1 value to each of the element inside object and return the result. The value of myList did not change but when we call the functions we saw the added value to elements of that object.

As my response to Is Functional Programming possible in Java?, I believe that it is not possible to have true functional programming in java. Because java is really designed to be OOP in which it extends imperative programming and improved it for maintainability. When the state of an object, variable etc, has changed then, that is already an imperative programming.

Body:
It may seems possible but it will not be a pure functional programming. It may results to imperative programming.

There is no asking why he mean by possible functional programming as mentioned by haylem. Here it is:

It depends what you mean by "functional programming" and by
  "possible".

Functional programming cannot have different definitions or meaning though it may have many explanations.

Like OOP, can we ask "what do you mean by OOP?".

Definitely there will be lot of explanations but it will just pertain to one objective, the objective of OOP.

The same applies to functional programming.

When we say functional meaning the programs consist of functions.

The role of the functions is to return an evaluated argument/parameter (argument is variable is the expression came when calling the function while parameter is variable that is a part of the function declaration).

Also functions will always return the same result when same arguments is passed. In that way it is easier to avoid bugs or debug future bugs. By functional programming we can avoid side effects like modifying global variable.

example in JavaScript:

function increment(lis){
    return lis.map(
        function (x){
            return x+2;
        }
    );
}

var myList = [4, 7, 2, 3];
console.log(increment(myList));
console.log(myList);

The function increment adds 1 value to each of the element inside object and return the result. The value of myList did not change but when we call the functions we saw the added value to elements of that object.

As my response to Is Functional Programming possible in Java?, I believe that it is not possible to have true functional programming in java. Because java is really designed to be OOP in which it extends imperative programming and improved it for maintainability. When the state of an object, variable etc, has changed then, that is already an imperative programming.


问:
Is there anything that can be done with recursion that can't be done with loops?
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines of code.

Are there any cases where a task can only be done using recursion, rather than a loop?

答: If you are programming in c++, and use c++11, then there is one thing that has to be done using recursions : constexpr functions. But the standard limits this to 512, as explained in this answer. Using loops in this case is not possible, since in that case the function can not be constexpr, but this is changed in c++14.</p>


问:
Is there any reason to use "plain old data" classes?
In legacy code I occasionally see classes that are nothing but wrappers for data. something like:

```<code>class Bottle {
   int height;
   int diameter;
   Cap capType;

   getters/setters, maybe a constructor
}
</code>```

My understanding of OO is that classes are structures for data and the methods of operating on that data. This seems to preclude objects of this type. To me they are nothing more than structs and kind of defeat the purpose of OO. I don't think it's necessarily evil, though it may be a code smell.

Is there a case where such objects would be necessary? If this is used often, does it make the design suspect?

答:
If this is the sort of thing you need, that's fine, but please, please, please do it like

```<code>public class Bottle {
    public int height;
    public int diameter;
    public Cap capType;

    public Bottle(int height, int diameter, Cap capType) {
        this.height = height;
        this.diameter = diameter;
        this.capType = capType;
    }
}
</code>```

instead of something like

```<code>public class Bottle {
    private int height;
    private int diameter;
    private Cap capType;

    public Bottle(int height, int diameter, Cap capType) {
        this.height = height;
        this.diameter = diameter;
        this.capType = capType;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getDiameter() {
        return diameter;
    }

    public void setDiameter(int diameter) {
        this.diameter = diameter;
    }

    public Cap getCapType() {
        return capType;
    }

    public void setCapType(Cap capType) {
        this.capType = capType;
    }
}
</code>```

Please.

Body:
If this is the sort of thing you need, that's fine, but please, please, please do it like

public class Bottle {
    public int height;
    public int diameter;
    public Cap capType;

    public Bottle(int height, int diameter, Cap capType) {
        this.height = height;
        this.diameter = diameter;
        this.capType = capType;
    }
}

instead of something like

public class Bottle {
    private int height;
    private int diameter;
    private Cap capType;

    public Bottle(int height, int diameter, Cap capType) {
        this.height = height;
        this.diameter = diameter;
        this.capType = capType;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getDiameter() {
        return diameter;
    }

    public void setDiameter(int diameter) {
        this.diameter = diameter;
    }

    public Cap getCapType() {
        return capType;
    }

    public void setCapType(Cap capType) {
        this.capType = capType;
    }
}

Please.


问:
What if a task waits for a resource in STCF algorithm?
I am a computer science student and I have an exam tomorrow on operating systems. I have the exam questions of past years and there is one scenario in a question. There are two tasks in the ready-to-run (I don't what's its name) queue. And the scheduling algorithm is Shortest Time to Completion First (STCF). And two semaphores, S1 and S2. Lets call the task one T1 and task two T2. Here is the scenario:

T1

```<code>{
    down(S1);
    // other codes
    up(S1);
}
</code>```

T2

```<code>{
    down(S1);
    down(S2);
    //Other code...
    up(S2);
    up(S1);
}
</code>```

T1 task comes to ready-to-run queue at time of 0th second and it takes 10 seconds to be completed. T2 comes to read-to-run queue at time of 3rd second and it takes 3 seconds to be completed.

Here is where I stuck. The T1 executes for 3 seconds, after that it will get preempted, since T2 comes and its time to completion is lesser. T2 will waits for the S1 semaphore to be upped to proceed further. What will processor do in this situation? Will it switch to T1 or it keeps try to process T2 since its completion time is lesser, and as a result deadlock?

答:
Assuming you are using a half-decent scheduler, then if a task tries to claim a semaphore that is not available, then that task gets put into a "blocked" or "waiting" state and will not be considered "ready to run" until the semaphore it is waiting for becomes available. Then the scheduler checks again the "ready to run" queue and selects a task from those in the queue to execute.

So, in your example, when T2 hits semaphore S1 it becomes blocked. At that point only T1 is "ready to run", so that task will be scheduled as it has the lowest time to completion among the tasks that could make progress when executed.

When T1 releases semaphore S1 (ups it), the scheduler will put T2 back in the "ready to run" queue and decides again which task to execute.


问:
Architecture/technology for implementing Management console
I'm having a distributed environment which include several machines under the same network , which are being controlled by another computer in another network which is also running a UI for doing the operations.
I want to be able to produce some simple parallel interface for being able to do maintenance on these machines.

I wonder what are my options to do so, as I want a simple  management console with UI.

Maybe implementing using sockets, sending json messages over the connection.

Maybe implement a kind of http server in each machine that will get the messages and act accordingly.

Can you please advise what other possibilities you have in mind and which are  the most suitable in your opinion.
I'm using python, and I prefer python oriented solutions.

答:
Implementing any form of remote-access will do really, but I would recommend putting a webserver in each process to allow remote control. The reason is partly because its easy to use standards-based comms here (ie a REST interface is easy to implement, easy to call, and easy to build services like security on top of) but also because it allows you to build a web UI into each process as well, so you could connect to each individual process via a browser and let it display a page with the same control functionality as you'd expose as a REST API.

That way you can control each process individually and control them all via a master control program.

Note that you will also have to implement some form of process discovery, unless you want to have to manually configure the location of each process.


问:
Is it better to check `c >= '0'` or `c >= 48`?
After a discussion with some my colleagues, I've a 'philosophical' question about how treat the char data type in Java, following the best practices.

Suppose a simple scenario (obviously this is only a very simple example in order to give a practice meaning to my question) where, given a String 's' as input, you have to count the number of numeric characters present in it.

These are the 2 possible solutions:

1)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= 48 && s.charAt(i) <= 57) {
            n++;
        }
    }
</code>```

2)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
            n++;
        }
    }
</code>```

Which of the two is more 'clean' and compliant with the Java best practices?

答:
Both are horrible, but the first is more horrible.

Both ignore Java's built-in capability to decide what characters are "numeric" (via methods in Character). But the first one not only ignores the Unicode nature of strings, assuming that there can be only 0123456789, it also obscures even this invalid reasoning by using character codes that make sense only if you know something about the history of character encodings.


答:
Neither. Let Java's built-in Character class figure it out for you.

```<code>for (int i = 0; i < s.length(); ++i) {
  if (Character.isDigit(s.charAt(i))) {
    ++n;
  }
}
</code>```

There are a few more character ranges than the ASCII digits that count as digits, and neither example you posted will count them. The JavaDoc for Character.isDigit() lists these character ranges as being valid digits:

Some Unicode character ranges that contain digits:

'\u0030' through '\u0039', ISO-LATIN-1 digits ('0' through '9')

'\u0660' through '\u0669', Arabic-Indic digits

'\u06F0' through '\u06F9', Extended Arabic-Indic digits

'\u0966' through '\u096F', Devanagari digits

'\uFF10' through '\uFF19', Fullwidth digits

Many other character ranges contain digits as well.

That being said, one should delegate to Character.isDigit() even with this list. As new Unicode planes are populated, the Java code will be updated. Upgrading the JVM could make old code work with new digit characters seamlessly. It is also DRY: by localizing the "is this a digit" code to one place referenced elsewhere, the negative aspects of code duplication (i.e. bugs) can be avoided. Finally, note the last line: this list is not exhaustive, and there are other digits.

Personally, I would rather delegate to the core Java libraries and spend my time on more productive tasks than "figuring what is a digit."

The only exception to this rule is if you really do need to test for the literal ASCII digits and not other digits. For example, if you are parsing a stream and only ASCII digits (as opposed to other digits) have special meaning, then it would not be appropriate to use Character.isDigit().

In that case, I would write another method, e.g. MyClass.isAsciiDigit() and put the logic in there. You get the same benefits of code reuse, the name is super-clear as to what it is checking, and the logic is correct.

Title: Is it better to check `c >= '0'` or `c >= 48`?

Body:
After a discussion with some my colleagues, I've a 'philosophical' question about how treat the char data type in Java, following the best practices.

Suppose a simple scenario (obviously this is only a very simple example in order to give a practice meaning to my question) where, given a String 's' as input, you have to count the number of numeric characters present in it.

These are the 2 possible solutions:

1)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= 48 && s.charAt(i) <= 57) {
            n++;
        }
    }
</code>```

2)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
            n++;
        }
    }
</code>```

Which of the two is more 'clean' and compliant with the Java best practices?

Body:
Neither. Let Java's built-in Character class figure it out for you.

for (int i = 0; i < s.length(); ++i) {
  if (Character.isDigit(s.charAt(i))) {
    ++n;
  }
}

There are a few more character ranges than the ASCII digits that count as digits, and neither example you posted will count them. The JavaDoc for Character.isDigit() lists these character ranges as being valid digits:

Some Unicode character ranges that contain digits:

'\u0030' through '\u0039', ISO-LATIN-1 digits ('0' through '9')

'\u0660' through '\u0669', Arabic-Indic digits

'\u06F0' through '\u06F9', Extended Arabic-Indic digits

'\u0966' through '\u096F', Devanagari digits

'\uFF10' through '\uFF19', Fullwidth digits

Many other character ranges contain digits as well.

That being said, one should delegate to Character.isDigit() even with this list. As new Unicode planes are populated, the Java code will be updated. Upgrading the JVM could make old code work with new digit characters seamlessly. It is also DRY: by localizing the "is this a digit" code to one place referenced elsewhere, the negative aspects of code duplication (i.e. bugs) can be avoided. Finally, note the last line: this list is not exhaustive, and there are other digits.

Personally, I would rather delegate to the core Java libraries and spend my time on more productive tasks than "figuring what is a digit."

The only exception to this rule is if you really do need to test for the literal ASCII digits and not other digits. For example, if you are parsing a stream and only ASCII digits (as opposed to other digits) have special meaning, then it would not be appropriate to use Character.isDigit().

In that case, I would write another method, e.g. MyClass.isAsciiDigit() and put the logic in there. You get the same benefits of code reuse, the name is super-clear as to what it is checking, and the logic is correct.


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答:
I do it tomorrow.

Getting Things Done is also immensely helpful.

I have a short attention span anyway, so these books help me keep my foc... what was I doing again?

OwnerDisplayName: Nick Gotch

Title: How to become a "faster" programmer?

OwnerDisplayName: Matthew Jones


问:
Uncle Bob's clean architecture - An entity/model class for each layer?
BACKGROUND :

I'm trying to use Uncle Bob's clean architecture in my android app. I studied many open source projects that are trying to show the right way to do it, and I found an interesting implementation based on RxAndroid.

WHAT I NOTICIED :

In every layer (presentation, domain and data), there's a model class for the same entity (talking UML). Plus, there are mapper classes that take care of object's transformation whenever the data is crossing the boundaries (from layer to another).

QUESTION :

Is it required to have model classes in every layer when I know that they'll all end up with the same attributes if all CRUD operations are needed? Or, is it a rule or a best practice when using the clean architecture?

答:
You actually got it right. And there is no violation of DRY because you accept SRP.

For example:
You have a business-Method createX(String name) then you may have a Method createX(String name) in the DAO-Layer, called within the business-Method. They may have the same signature and maybe there is only a delegation but they have different purposes. You can also have a createX(String name) on the UseCase. Even then it is not redundant. What I mean with this is: Same signatures do not mean same semantics. Choose other names for it to have the semantics clear. Naming itself this doesn't affect SRP at all.

The UseCase is responsible for application-specific logic, the business object is responsible for application-independent logic and the DAO is responsible for storing.

Due to the different semantics all layers may have their own representation and communication model. Often you see "entities" as "business objects" and often you do not see the necessity to separate them. But in "huge" projects the effort should be taken to properly separate the layers. The greater the project the possibility rises that you need the different semantics represented in different layers and classes.

You can think of different aspects of the same semantic. A User-Object has to be displayed on the screen, it has some inner consistency rules and it must be stored somewhere. Each aspect should be represented in a different class (SRP). Creating the mappers can be pain in the ass so in most projects I worked in these aspects are melted into one class. This is clearly a violation of SRP but nobody really cares.

I call the application of clean architecture and S.O.L.I.D. "not socially acceptable". I would work with it if I am allowed to. Currently I am not allowed to do it. I wait for the moment we have to think about taking S.O.L.I.D. seriously.

OwnerDisplayName: Rami Jemli


问:
Does this code solve the square/rectangle Liskov Substitution Principle example?
I just wanted to check that I understand the LSP correctly and can solve it. I am taking the classic rectangle/square problem and attempting a solution:

class Rectangle{
    public $width;
    public $height;

    function setWidth($width){
        $this->width = $width;
    }

    function setHeight($height){
        $this->height = $height;
    }
}

class Square extends Rectangle{

    function setWidth($width){
        $this->width = $width;
        $this->height = $width;
    }

    function setHeight($height){
        $this->height = $height;
        $this->width = $height;
    }
}
```

<p>If you had some code like:</p>

<pre class="lang-php prettyprint-override"><code>function changeSize(Rectangle $rect){
  $rect->setWidth(10);
  $rect->setHeight(30);
  $this->assertEquals(10,$rect->width);
  $this->assertEquals(30,$rect->height);
}
</code>```

Then obviously rectangles and squares are not interchangeable, as square introduces a constraint to the parent class. Therefore, a square should not inherit from rectangles.

But surely we can agree that both square and rectangle are four sided shapes? This is my proposed solution, based on this premise:

abstract class AFourSidedShape{
    public $width;
    public $height;

    abstract public function __construct($width,$height);

    public function scaleUp($percentage){
        $this->height = $this->height + (($this->height / 100) * $percentage);
        $this->width = $this->width + (($this->width / 100) * $percentage);
    }

    public function scaleDown($percentage){
        $this->height = $this->height - (($this->height / 100) * $percentage);
        $this->width = $this->width - (($this->width / 100) * $percentage);
    }
}

class Rectangle extends AFourSidedShape{
    function __construct($width, $height){
        $this->width = $width;
        $this->height = $height;
    }
}

class Square extends AFourSidedShape{
    function __construct($width, $height){
        if($width != $height){
            throw new InvalidArgumentException('Sides must be equal');
        }else{
            $this->width = $width;
            $this->height = $height;
        }
    }
}
```

<p>Our client code should be changed to something like:</p>

<pre class="lang-php prettyprint-override"><code>function changeSize(AFourSidedShape $shape){
  $origWidth = $shape->width;
  $origHeight = $shape->height;
  $shape->scaleUp(10);
  $this->assertEquals($origWidth + (($origWidth/100) * 10),$shape->width);
  $this->assertEquals($origHeight + (($origHeight/100) * 10),$shape->height);
}
</code>```

My theory is: rectangles and squares really are both foursidedshapes, so there shouldn't be a problem with inheriting from the foursidedshape abstract class. Whilst the square is still adding extra constraints in the constructor (i.e. throwing an error if the sides aren't equal), it shouldn't be a problem since we haven't implemented the constructor in the abstract parent class, and so client code shouldn't make assumptions about what you can/cannot pass into it anyway.

My question is: have I understood LSP, and does this new design solve the LSP problem for square/rectangle?

When using interfaces as suggested:

interface AFourSidedShape{
    public function setWidth($width);
    public function setHeight($height);
    public function getWidth();
    public function getHeight();
}

class Rectangle implements AFourSidedShape{
    private $width;
    private $height;

    public function __construct($width,$height){
        $this->width = $width;
        $this->height = $height;
    }

    public function setWidth($width){
        $this->width = $width;
    }

    public function setHeight($height){
        $this->height = $height;
    }

    //getwidth, getheight
}

class Square implements AFourSidedShape{
    private $width;
    private $height;

    public function __construct($sideLength){
        $this->width = $sideLength;
        $this->height = $sideLength;
    }

    public function setWidth($width){
        $this->width = $width;
        $this->height = $width;
    }

    public function setHeight($height){
        $this->height = $height;
        $this->width = $height;
    }

    //getwidth, getheight
}
```

答:
I'm going to assume you are trying to solve the "Typical Violation" section of the LSP Wikipedia article. If that's the case, you haven't solved it and the section states clearly why. Specifically, start with the setup: "Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height." LSP states that the subclass should be able to stand-in for the super class.

But, it's not just that! That's what you and your commenters are missing. If it was just a matter of torturing your design until you could make the swap (everything is a AFourSidedShape), you could simply design some generic object (no shape or behavior), have everything inherit from the object, and then swap in specific implementations. Think about what would happen if you did that. You'd constantly be interrogating the objects to determine what they can do and/or violating their post conditions That's what the LSP hates.

So in your case, a AFourSidedShape doesn't really solve anything because you'd constantly be checking if your specific implementations were Rectangles or Squares to ensure post conditions are correct -- a Square's width can magically change when you update its height but not a Rectangle's. That's what the sections means when it says, "these methods will weaken (violate) the postconditions for the Rectangle setters." You can't get away from less-than-ideal behavior. It's a tradeoff. (Unless you make your objects immutable! Hooray for immutability!)

Don't feel bad. The Rectangle/Square with getters/setters for width/height problem is meant to be unsolvable in the trivial sense. It's a great, simple example of why LSP is difficult in practice.

ContentLicense: CC BY-SA 4.0


问:
How can I use a framework like Bootstrap when I already have designs from a design team
We are about to start an AngularJS project. In fact, the CMS will be AEM (Adobe Experience Manager). I'm now looking into the CSS/layout framework, and whether its worth using something like Bootstrap, when the design team/client has already decided what it will look like.

From what I understand, Bootstrap is very useful, and yes you can make beautiful production ready sites with bootstrap, but I feel Bootstrap can constrict the design, and often Bootstrap leads/tells you how it needs to look, which could cause problems with our design team.

More detail:

An example is the grid system. It gets generalised into a 12 column grid, and the content is responsive to that. You can't specify to the cm how you want that column or content to look. Perfect in most cases, too much restriction would make it NOT responsive, and more 'adaptive' to mobile, as your being very specific.

But my question is when you have a design team that has already created wireframes and specified how it should all look, should you still use something like Bootstrap. (Or any others like Foundation, Skeleton, Pure, Concise...)

Is it better to just not use them at all, or is there still very much a need for them.

What about just a layouting framework which is not responsive? I mean, the requirement is for it to work on a tablet, but still, there will be different sized tablets, so responsive still needs to be considered, and what if there is a future need for it to work on mobile, its better to consider that upfront and code in just in case.

I realise my question might not be too clear, but its a hard one to explain without the above fluff. And it better not be closed due to opinionated, as im not asking for a comparison of frameworks, more rather, is a framework the right way to go in this instance. I'll happily re-word if it needs it though.

However, if there is something I missed, something like a middle ground between fully custom CSS and using something like Bootstrap, please mention.

答:
One still may able to use Bootstrap with pre-existing designs, but more customization will be needed.

Bootstrap is used because one can get a responsive web site up very quickly with minimal additional work.   This means less cost and time spent on making your web site responsive.

If designs are done up front, the value of using a framework like Bootstrap may be diminished as one will have to spend more time customizing the CSS  and making the Bootstrap framework conform to your design.  One can make a web site responsive without Bootstrap, its just more time and effort.  Bootstrap can also be customized as well with custom CSS code but leveraging what comes out of the box will be diminished.

Look at the current design and see how well it fits into the Bootstrap framework.  If there are issues, try and get your stakeholders to buy down on some of the designs so more of the framework can be utilized.  If they are unwilling to yield to any changes, simply tell them it will take more time, money, and effort as more customization is required.


答:
Practice. That, and getting your hands on productivity tools that allow you to go faster.

For example (you didn't mention the platform on which you work), in the .NET environment, there's Resharper.

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,


答:
With the LSP and inheritance basically means: the child class can do everything that the parent class can and a bit more.

And here comes the problem:

For a square : you can fold a square into a half-square triangle.
Which mean you could make a method: "makesquaretriangle".
This is not true for all rectangles.

For a rectangle : If you multiply the height by a factor, and the width by the inverse of that factor, it will still have the same surface area.
Which means you could make a method: "doublemyheightbutkeepsurface" which doubles the height and automatically halves the width.

This is not true for a square.

So you see, both square and rectangle have methods that don't make sense on the other, that's why they can't always be substituted. And why they can't inherit from each other either way.

The LSP is specifically for the cases where you want to either inherit A from B or want to inherit B from A, but can't.
Other cases where you inherit both B and A from a common base class are out of the scope of the LSP.
So your solution has nothing to do with the LSP.

Title: Does this code solve the square/rectangle Liskov Substitution Principle example?

Body:
I just wanted to check that I understand the LSP correctly and can solve it. I am taking the classic rectangle/square problem and attempting a solution:

class Rectangle{
    public $width;
    public $height;

    function setWidth($width){
        $this->width = $width;
    }

    function setHeight($height){
        $this->height = $height;
    }
}

class Square extends Rectangle{

    function setWidth($width){
        $this->width = $width;
        $this->height = $width;
    }

    function setHeight($height){
        $this->height = $height;
        $this->width = $height;
    }
}
```

<p>If you had some code like:</p>

<pre class="lang-php prettyprint-override"><code>function changeSize(Rectangle $rect){
  $rect->setWidth(10);
  $rect->setHeight(30);
  $this->assertEquals(10,$rect->width);
  $this->assertEquals(30,$rect->height);
}
</code>```

Then obviously rectangles and squares are not interchangeable, as square introduces a constraint to the parent class. Therefore, a square should not inherit from rectangles.

But surely we can agree that both square and rectangle are four sided shapes? This is my proposed solution, based on this premise:

abstract class AFourSidedShape{
    public $width;
    public $height;

    abstract public function __construct($width,$height);

    public function scaleUp($percentage){
        $this->height = $this->height + (($this->height / 100) * $percentage);
        $this->width = $this->width + (($this->width / 100) * $percentage);
    }

    public function scaleDown($percentage){
        $this->height = $this->height - (($this->height / 100) * $percentage);
        $this->width = $this->width - (($this->width / 100) * $percentage);
    }
}

class Rectangle extends AFourSidedShape{
    function __construct($width, $height){
        $this->width = $width;
        $this->height = $height;
    }
}

class Square extends AFourSidedShape{
    function __construct($width, $height){
        if($width != $height){
            throw new InvalidArgumentException('Sides must be equal');
        }else{
            $this->width = $width;
            $this->height = $height;
        }
    }
}
```

<p>Our client code should be changed to something like:</p>

<pre class="lang-php prettyprint-override"><code>function changeSize(AFourSidedShape $shape){
  $origWidth = $shape->width;
  $origHeight = $shape->height;
  $shape->scaleUp(10);
  $this->assertEquals($origWidth + (($origWidth/100) * 10),$shape->width);
  $this->assertEquals($origHeight + (($origHeight/100) * 10),$shape->height);
}
</code>```

My theory is: rectangles and squares really are both foursidedshapes, so there shouldn't be a problem with inheriting from the foursidedshape abstract class. Whilst the square is still adding extra constraints in the constructor (i.e. throwing an error if the sides aren't equal), it shouldn't be a problem since we haven't implemented the constructor in the abstract parent class, and so client code shouldn't make assumptions about what you can/cannot pass into it anyway.

My question is: have I understood LSP, and does this new design solve the LSP problem for square/rectangle?

When using interfaces as suggested:

interface AFourSidedShape{
    public function setWidth($width);
    public function setHeight($height);
    public function getWidth();
    public function getHeight();
}

class Rectangle implements AFourSidedShape{
    private $width;
    private $height;

    public function __construct($width,$height){
        $this->width = $width;
        $this->height = $height;
    }

    public function setWidth($width){
        $this->width = $width;
    }

    public function setHeight($height){
        $this->height = $height;
    }

    //getwidth, getheight
}

class Square implements AFourSidedShape{
    private $width;
    private $height;

    public function __construct($sideLength){
        $this->width = $sideLength;
        $this->height = $sideLength;
    }

    public function setWidth($width){
        $this->width = $width;
        $this->height = $width;
    }

    public function setHeight($height){
        $this->height = $height;
        $this->width = $height;
    }

    //getwidth, getheight
}
```


答:
The LSP is about the contract of a class, and that inherited classes must still fulfill the same contract as their base class. An interface just in code will typically only define parts of that contract, mainly the syntactical part, and the semantics might be partially given by descriptive names of the methods or the parameters. Other parts of the contract are often just defined in comments, by adding "assertion statements", by making use of specific language features, or they might be encoded into unit tests.

Thus if you solved the LSP violation really, depends on the full semantic contract of your interface. If the contract looks like this (which is IMHO the more obvious behaviour):

```<code>// contract: a four sided shape is an object with two individual, independent
// properties "width" and "height"
interface AFourSidedShape{
    public function setWidth($width);
    public function setHeight($height);
    public function getWidth();
    public function getHeight();
}
</code>```

then Square class does not fulfill the same contract as its base class, so it still violates the LSP. One could write that more formally in terms of "post conditions", checking that each time you call setHeight, the value of getWidth does not change, and vice versa.

If, however, your semantic contract looks like this:

```<code> // contract: a four sided shape is an object with two
 // properties "width" and "height" which must not
 // be assumed to be independent; maybe changing one can change the other
 interface AFourSidedShape{
     // ...
 }
</code>```

then there is no LSP violation any more. From your question and the way you describe the constructor constraints, I guess that is the contract you have in mind.  However, the latter might violate the principle of least astonishment, a "setter" which for some objects changes another value, and for others it does not, can be mind-boggling to the average user of your class. Better avoid to put such setters in the common interface, LSP obeyed or not.

Side note: of course, the original Square/Rectangle problem can be understood as "is there an implementation where Square derives from Rectangle or vice versa directly which does not violate the LSP". If one reads it this way, then @ScantRoger is correct and your design solves a different problem. However, I read the problem quite differently as is there a way to incorporate inheritance to deal with rectangles and squares in a generic manner without violating LSP, and for this problem the answer is "yes, your suggestion will solve that problem".

Body:
The LSP is about the contract of a class, and that inherited classes must still fulfill the same contract as their base class. An interface just in code will typically only define parts of that contract, mainly the syntactical part, and the semantics might be partially given by descriptive names of the methods or the parameters. Other parts of the contract are often just defined in comments, by adding "assertion statements", by making use of specific language features, or they might be encoded into unit tests.

Thus if you solved the LSP violation really, depends on the full semantic contract of your interface. If the contract looks like this (which is IMHO the more obvious behaviour):

// contract: a four sided shape is an object with two individual, independent
// properties "width" and "height"
interface AFourSidedShape{
    public function setWidth($width);
    public function setHeight($height);
    public function getWidth();
    public function getHeight();
}

then Square class does not fulfill the same contract as its base class, so it still violates the LSP. One could write that more formally in terms of "post conditions", checking that each time you call setHeight, the value of getWidth does not change, and vice versa.

If, however, your semantic contract looks like this:

 // contract: a four sided shape is an object with two
 // properties "width" and "height" which must not
 // be assumed to be independent; maybe changing one can change the other
 interface AFourSidedShape{
     // ...
 }

then there is no LSP violation any more. From your question and the way you describe the constructor constraints, I guess that is the contract you have in mind.  However, the latter might violate the principle of least astonishment, a "setter" which for some objects changes another value, and for others it does not, can be mind-boggling to the average user of your class. Better avoid to put such setters in the common interface, LSP obeyed or not.

Side note: of course, the original Square/Rectangle problem can be understood as "is there an implementation where Square derives from Rectangle or vice versa directly which does not violate the LSP". If one reads it this way, then @ScantRoger is correct and your design solves a different problem. However, I read the problem quite differently as is there a way to incorporate inheritance to deal with rectangles and squares in a generic manner without violating LSP, and for this problem the answer is "yes, your suggestion will solve that problem".


答:
In a practical way, that has been solved many times.

Programs like Inkscape, Photoshop, The Gimp, Illustrator and so on don't have separate rectangle and square tools in their palettes. They have only one tool for drawing rectangles and squares. And they don't call it "quadrilateral", they call it rectangle. Some even call it "rectangles and squares tool" so confused users wouldn't migrate to other apps that would allow them to draw squares.

So it seems to me that they found a way for it to work for them. And I suspect what they have done is assume a square is just a rectangle with equal height and width. They even allow you, by using the shift key when drawing, to lock it in a way that you can create a square.

I don't really think those programs switch from a rectangle object to a completely different and incompatible square object when you press shift, only to fall-back to an incompatible rectangle when you release Shift. That could be easily corroborated by downloading the source code of those programs that are open-source, like Inkscape or The Gimp.

So I think that when you changed the design from inheritance of a superclass to implementation of an interface, you "kinda" solved it.

Because in the case of inheritance you are stating that a square is a rectangle, which is false. In the other hand when you go with implementing an interface you are saying that a square can act as a rectangle. In that scenario what the methods do or don't do under the hood is an implementation detail. Better yet if you forget about squares altogether you are fine because nothing prevents you from creating a rectangle with equal sides.

So it's really a philosophical problem and not a practical one.

In Wikipedia definition

A square...It can also be defined as a rectangle in  which two
adjacent sides have equal length.


答:
Avoid polishing your code to the perfection, just make it work. That's what the business expects.

But often, increasing speed implies sacrificing quality.

Title: How to become a "faster" programmer?


问:
Where to describe architectural problems?
I joined the middle of a middle size project, which runs already for several years. One of problems is that the document describing the architecture was never written. Now I was assigned a task to write the architecture description.

During the time I working on this project, I gathered all information I needed to write the document. Since I also added some features, I identified some pieces of code, which are clearly breaking the architecture as it is described.

For example, the GUI was supposed to be a thin layer, without business logic. That is what I was told. The implementation contains lots of logic.

My boss assigned me the task, to write the document describing the architecture of the system. The target audience are current and future developers working on the project. I need to describe what should be, but I also need to describe the deviations somehow.

So, where should I describe these problems? Bugs tracking software? Or should I describe implementation's deviations from the architecture in the document describing the architecture of the system?

答:
I would be inclined to write an architectural document organised into 3 main sections.

The first introducing the design/architecture that was initially intended. This will allow new developers/readers to get an idea for what the system is supposed to do and should obviously be tied to the requirements/usecases etc.

The second section should explain very clearly exactly what the architecture actually is. This allows the new developers/readers to get an idea of the current state of play and what they are dealing with if they look at the software (and potentially other documentation). This section should clearly indicate the difference between what was intended and reality as this will most likely hightlight things that are either very wrong with the original architecture (hopefully not too many!) and areas where shortcuts/hacks (probably a fair few if there was a large degree of pressure on the dev team) have been made and requirements are not being fulfilled or the software is beggining to look 'poorly' designed i.e fragile, instable, un-portable.

Finally I think a section detailing the recommendations for what needs to happen now. This should be any changes to the architecture/design and a roadmap for changes to the software at present in order to make your vision become a reality.

I think this covers (at high level) what needs to be captured. How you do this in terms of the subsections of the document or bug tracking software you employ is down to the domain you are working in/personal preference/team size/budget/time scale etc.


答:
If you ever write an application in C that uses EBCDIC as the basic character set and needs to process ASCII characters then use 48 and 57. Are you doing that? I don't think so.

About using isDigit(): it depends. Are you writing a JSON parser? Only 0 to 9 are accepted as digits, so don't use isDigit(), check for >= '0' and <= '9'. Are you processing user input? Use isDigit() as long as the rest of your code actually can handle the string and turn it into a number correctly.


问:
What is the difference between <? extends Foo> and <Foo>
I seem to have a misunderstanding about the difference between <Foo> and <? extends Foo>. From my understanding, if we had

```<code>ArrayList<Foo> foos = new ArrayList<>();
</code>```

This indicates that objects of type Foo can be added to this array list. Since subclasses of Foo are also of type Foo, they can also be added without an error, as illustrated by

```<code>ArrayList<Foo> foos = new ArrayList<>();
foos.add(new Foo());
foos.add(new Bar());
</code>```

where Bar extends Foo.

Now, say I had defined foos as

```<code>ArrayList<? extends Foo> foos = new ArrayList<>();
</code>```

My current understanding is that this expresses some unknown type that extends Foo. I take this to mean that any objects that are a subclass of Foo can be added to this list; meaning that there is no difference between ArrayList<Foo> and ArrayList<? extends Foo>.

To test this, I tried to write the following code

```<code>ArrayList<? extends Foo> subFoos = new ArrayList<>();
subFoos.add(new Foo());
subFoos.add(new Bar());
</code>```

but was prompted with the following compilation error

```<code>no suitable method found for add(Foo)
method java.util.Collection.add(capture#1 of ? extends Foo) is not applicable
(argument mismatch; Foo cannot be converted to capture#1 of ? extends Foo)

no suitable method found for add(Bar)
method java.util.Collection.add(capture#2 of ? extends Bar) is not applicable
(argument mismatch; Bar cannot be converted to capture#2 of ? extends Bar)
</code>```

Based on my current understanding, I can see why I might not be able to add a Foo to a list of <? extends Foo>, because it is not a subclass of itself; but I am curious as to why I cannot add a Bar to the list.

Where is the hole in my understanding?

答:
As you have discovered by yourself, an ArrayList declared as ArrayList<? extends Foo> subFoos = new ArrayList<>(); would not be very useful.

In order to see the usefulness of <? extends T> consider this:

```<code>List<Foo> collect( List<? extends Foo> a1, List<? extends Foo> a2 )
{
    List<Foo> collected = new ArrayList<>();
    collected.addAll( a1 );
    collected.addAll( a2 );
    return collected;
}
</code>```

which can later be used as follows:

```<code>List<Foo> foos = collect( new ArrayList<Foo>(), new ArrayList<Bar>() );
</code>```

or as follows:

```<code>List<Foo> foos = collect( new ArrayList<Bar>(), new ArrayList<Foo>() );
</code>```

note that none of the above would have worked if the collect method had been declared as follows:

```<code>List<Foo> collect( List<Foo> a1, List<Foo> a2 )
</code>```

Body:
As you have discovered by yourself, an ArrayList declared as ArrayList<? extends Foo> subFoos = new ArrayList<>(); would not be very useful.

In order to see the usefulness of <? extends T> consider this:

List<Foo> collect( List<? extends Foo> a1, List<? extends Foo> a2 )
{
    List<Foo> collected = new ArrayList<>();
    collected.addAll( a1 );
    collected.addAll( a2 );
    return collected;
}

which can later be used as follows:

List<Foo> foos = collect( new ArrayList<Foo>(), new ArrayList<Bar>() );

or as follows:

List<Foo> foos = collect( new ArrayList<Bar>(), new ArrayList<Foo>() );

note that none of the above would have worked if the collect method had been declared as follows:

List<Foo> collect( List<Foo> a1, List<Foo> a2 )


答: Turn off the computer.  Grab a pencil and some paper.  Sketch out your design.  Review it with your peers.  Then write the code.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: gatorfax


问:
Why '-5<(unsigned)5' is false?
In c programming why I am getting 0 zero for this? Why -5<(unsigned)5 is  false?

```<code>main(){
printf("%d",-5<(unsigned)5);
getch();
}
</code>```

答:
Because it's doing it as an unsigned comparison, which means it's actually checking if UINT_MAX - 4 < 5, which obviously is false.

IMO having no unsigned types is one of the few things Java really got right.  It means you don't get headaches like this.

Title: Why '-5<(unsigned)5' is false?