问:
Adding new functionality to all of shelve.Shelf's subclasses in Python
In order to avoid the overhead associated with the shelve module's writeback option I'm interested in putting together a shelf class that only accepts hashable values, with hashability being a proxy for immutability. So I'd like to subclass shelve.Shelf and override the __set__ method. The catch is that shelve.open can return one of a number of different classes (e.g., Dbfilenameshelf), and I'd like my code to allow shelve this flexibility.

Ideally a solution would have the following properties:

No need to wrap every function that Shelf provides, as in: def keys(self): return self._shelf.keys()

Will not break if Python adds new methods to Shelf or new subclasses of Shelf

Avoiding fragility, by which I mean doing something complicated that could easily trip up someone (conceivably me) who is modifying or using the code months or years down the road. An example in this context would be reassigning Shelf.__set__, as in Shelf.__set__ = my_func. To me defining a new __getattr__ as @Winston hesitantly offers seems moderately fragile--I take it that's why he suggests it only with hesitation

Less important but still desirable would be:

Consistent with object-oriented design principles. It seems to me that the new class here is a shelf, not that it has a shelf. And probably not both (it's not a shelf which contains another shelf)

答: Don't subclass shelve.Self, instead define a new class with a constructor that that calls shelve.open. Implement the method of interest by calling the actual methods on the returned shelf object.


问:
Are the required parameters of a function called dependencies?
I'm studying dependency injection and I want to know if required function parameters can be considered dependencies.

I'd just like to make sure before I go around referring to them dependencies and that turns out to not be exactly accurate.

```<code>function doSomething(required){

    if(required !== null){

        // do stuff

    }

}
</code>```

Are the required parameters of a function called dependencies?

答:
Not necessarily.

If you look at the Wikipedia Article, you'll find that a Dependency is considered a service.  In practical terms, this is going to be an object of some sort (a reference type to be more exact). While that object is going to be passed to some class constructor as a parameter, not all constructor parameters are service objects, and therefore not all parameters are dependencies in that sense.

Most IoC Containers are tasked with creating objects, not satisfying primitive (value type) constructor parameters.

ContentLicense: CC BY-SA 3.0


问:
Why does Haskell's built in max function run faster than mine?
I noticed that for some reason, Haskell's built in max function (which returns the greatest of two numbers) runs much faster than the one I wrote, even though they are essentially identical.

From this site: http://www.haskell.org/onlinereport/standard-prelude.html,
I found that the standard max function is defined as:

```<code>    max x y
     | x <= y    =  y
     | otherwise =  x
</code>```

which is capable of executing

```<code>foldr max 0 [0..10000000]
</code>```

in 7.6 seconds (my laptop is in super power saving mode)

I wrote the exact same function though, and ran it, and

```<code>foldr myMax 0 [0..10000000]
</code>```

took an average of 23.74 seconds

The two functions look identical, except that the built-in max doesn't seem to have a type signature (unless its hidden somewhere.)

Does anyone know what might be going on here? I seriously doubt that a built in function will run more than three times faster than an identical, user defined one. To me that would be very strange.

(When I say that they're identical, I mean literally clones of each other. Just to test, I C&P'd it right out of the Prelude, and it's still significantly slower.)

Edit: I thought about it more, and I think it might have something to do with the included functions being pre-compiled, where-as my functions are being interpreted via GHCI (Which would make sense then). I'll leave this up in case someone has a better answer, but I suspect this to be the cause.

(One thing I realized that I don't understand though is why GHCI says that's it compiled my code after an edit, but then goes on the say that's it's interpreting it. You don't interpret compiled code do you?)

答:
When you loaded the definition for your own max function into ghci, you may have not noticed that ghci indicated that it was interpreted (something along these lines):

```<code>Prelude> :l mymax.hs
[1 of 1] Compiling Main             ( mymax.hs, interpreted )
Ok, modules loaded: Main.
</code>```

In order to really benchmark performance, compile your definition with ghc and run the test again. It should execute at about the same speed as the builtin max function. Don't forget the include optimization too (-O2).

Body:
When you loaded the definition for your own max function into ghci, you may have not noticed that ghci indicated that it was interpreted (something along these lines):

Prelude> :l mymax.hs
[1 of 1] Compiling Main             ( mymax.hs, interpreted )
Ok, modules loaded: Main.

In order to really benchmark performance, compile your definition with ghc and run the test again. It should execute at about the same speed as the builtin max function. Don't forget the include optimization too (-O2).


问:
Confused on how to properly employ a Repository Pattern with Service/Business Layer on top
I'm building a ASP.NET Web Api 2 solution for learning purposes, and I've hit a snag. I was wondering if anyone could tell me what exactly it is that I'm missing.

My Web Api solution has 4 Layers:

Data, which contains the Data Models ( POCOs ), Fluent API Mappings, EF Context, Migrations and Seeding

Repository, which implements CRUD for all Data Models and returns the business Models

Domain / Service / Business which supplies the IRepository interface, and should hold services which implement the application's business logic. Also contains the Business Models.

Web, the Web Api controllers and DI / IoC to tie everything together.

References are as follows: Data < Repository > Domain

Web references all 3 layers for DI.

The idea behind the separate domain layer is that it is completely oblivious to anything that happens in the Data or Repository layer. It simply outlines its requirements by providing the IRepository for the Repository layer, and the Business Models that it wants to get as a result. It's up to the Repository layer to meet the Domain Layer's requests.

Here is my conundrum:

Since Domain has no ties to Data, it does not know anything about the structure of the Data model. This means that the repository layer needs to convert everything to the Business Model before returning it. - I suppose I could return it as a generic object, and then map the generic object to the business model inside the Domain Layer. Would that be more appropriate?

Again, since Domain does not know anything about the Data Model, I can't pass any expressions to apply on the data set to my Repository. This means that for every property I want to WHERE, I'd have to create a POCO specific Repository with matching IBussinessModelRepository which outlines it's requirements, and then implement that requirement. This quickly gets tedious though, as it calls for a bunch of "GetByProp1", "GetByProp2" - monkey code central.

What if I want to create a composite business model that requires a complex query to hydrate? Is my only option to create yet another IBusinessRepository with a matching Repository and then write the complex query in the repository layer? If that is the case, then it feels like the service layer is mostly just another step that passes along non-crud requests to specific repositories.

Is it proper for web API controllers to send requests directly to the repository? It would seem pretty silly to route all CRUD requests through the service layer, which just passes the request to the repository layer anyway. No, it's not as the service layer should be the entry point for all operations. ( With Web just acting as a consumer of the services offered. )

I currently don't use a Unit of Work because there is a lot of mixed opinions when it comes to UoW + EF. I'm not yet experienced enough to be on either side of the fence. Would a UoW be helpful in this scenario?

I feel like I am missing a vital part in what makes this pattern / layer approach tick.

I know that I could easily proceed by cheating ( i.e. give service access to data specific stuff like the context ), but I'm more interested in learning how to do it the proper way.

The research I have done so far yielded results that vary wildly:

From the Repository using AutoMapper to change the type to the business model without actually executing the query, allowing the service layer to pass Business Model Expressions which can then be applied and then running the query, returning the mapped result -- sounds great, except that approach does not seem to work for me due to AutoMapper not being able to deal with my Models having recursive nav properties.

To the service layer just interfacing directly with the POCOs. ( And thus having direct access to the DAL )

What am I missing?

Edit to explain more about my code:

My Generic Repository on Github contains CRUD methods like this one:

```<code>public abstract class RepositoryBase<TData, TDomain, TId> : IRepository<TDomain, TId> where TDomain : EntityBase<TId>, new() where TData : class, IDataEntity<TId>, new()
{
    private readonly ShortStuffContext _context;

    public RepositoryBase(ShortStuffContext context)
    {
        _context = context;
    }

    public IEnumerable<TDomain> GetAll()
    {
        return _context.Set<TData>().BuildQuery<TData, TDomain>();
    }
}
</code>```

BuildQuery is a LINQ Extension which either grabs all entities, or can take a expression to fetch a single entity and then uses ValueInjecter to map the Data Model to the Domain Model.

The repository methods are requested by the Domain Layer via Interface:

```<code>public interface IRepository<TDomain, TId> where TDomain : EntityBase<TId>
{
    IEnumerable<TDomain> GetAll();
}
</code>```

The RepositoryBase is extended by Repositories for the individual POCOs, which currently sit empty, only providing TData, TDomain and TId to the Repository Base:

```<code>public class UserRepository : RepositoryBase<Data.Entities.User, User, decimal>
{
    public UserRepository(ShortStuffContext context)
        : base(context)
    {
    }
}
</code>```

Which can be requested by the Domain Layer via Constructor Injection IRepository<User, decimal> UserRepository through a ninject InRequestScope binding.

答:
How large is your application?  There's a good chance you're overthinking this.  Unless the application is a large, enterprise-grade application, the high degree of loose coupling you are advocating is probably unnecessary.

If you decide that this level of loose coupling  is still necessary, create a service layer that returns "service" objects.  This fulfills a similar function to View Models in MVC.  You will then write code in your service layer that maps objects from your domain model to your service model.

Note that part of your struggle may be due to the fact that, while your Data Repository is returning CRUD objects, your Service Layer should be returning the result of actions.  For example:

```<code>public InvoiceView GetInvoice(int invoiceID);
</code>```

returns a InvoiceView object containing whatever data you wish to expose to the public, including Name, Address, Line Items and so forth, from several different tables/objects in your domain.

```<code>public class InvoiceView
{
    public int InvoiceID;
    public Address ShippingAddress;
    public Address BillingAddress;
    public List<LineItem> LineItems;
    ...
}
</code>```

Similarly, there will be Service Layer methods that simply performs an action and returns an object indicating the result of the action:

```<code>public TransactionResult Transfer(
    int sourceAccountID, int targetAccountID, Money amount, ValidationToken token);
</code>```

IMPORTANT: You'll never be able to completely decouple from your data.  Your consumer will always have to have some knowledge of the data, even if it's just an object ID or UUID.

ContentLicense: CC BY-SA 4.0

Body:
How large is your application?  There's a good chance you're overthinking this.  Unless the application is a large, enterprise-grade application, the high degree of loose coupling you are advocating is probably unnecessary.

If you decide that this level of loose coupling  is still necessary, create a service layer that returns "service" objects.  This fulfills a similar function to View Models in MVC.  You will then write code in your service layer that maps objects from your domain model to your service model.

Note that part of your struggle may be due to the fact that, while your Data Repository is returning CRUD objects, your Service Layer should be returning the result of actions.  For example:

public InvoiceView GetInvoice(int invoiceID);

returns a InvoiceView object containing whatever data you wish to expose to the public, including Name, Address, Line Items and so forth, from several different tables/objects in your domain.

public class InvoiceView
{
    public int InvoiceID;
    public Address ShippingAddress;
    public Address BillingAddress;
    public List<LineItem> LineItems;
    ...
}

Similarly, there will be Service Layer methods that simply performs an action and returns an object indicating the result of the action:

public TransactionResult Transfer(
    int sourceAccountID, int targetAccountID, Money amount, ValidationToken token);

IMPORTANT: You'll never be able to completely decouple from your data.  Your consumer will always have to have some knowledge of the data, even if it's just an object ID or UUID.


问:
Why is software OS specific?
I'm trying to determine the technical details of why software produced using programming languages for certain operating systems only work with them.

It is my understanding that binaries are specific to certain processors due to the processor specific machine language they understand and the differing instruction sets between different processors. But where does the operating system specificity come from?
I used to assume it was APIs provided by the OS but then I saw this diagram in a book:

Operating Systems - Internals and Design Principles 7th ed - W. Stallings (Pearson, 2012)

As you can see, APIs are not indicated as a part of the operating system.

If for example I build a simple program in C using the following code:

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

main()
{
    printf("Hello World");

}
</code>```

Is the compiler doing anything OS specific when compiling this?

答:
Is the compiler doing anything OS specific when compiling this?

Probably. At some point during the compiling and linking process, your code is turned into an OS-specific binary and linked with any required libraries. Your program has to be saved in a format that the operating system expects so that the OS can load the program and start executing it. Furthermore, you're calling the standard library function printf(), which at some level is implemented in terms of the services that the operating system provides.

Libraries provide an interface -- a layer of abstraction from the operating system and the hardware -- and that makes it possible to recompile your program for a different operating system or different hardware. But that abstraction exists at the source level -- once the program is compiled and linked, it's connected to a specific implementation of that interface that's specific to a given OS.

Title: Why is software OS specific?


答:
As you can see, APIs are not indicated as a part of the operating system.

I think you are reading too much into the diagram. Yes, an OS will specify a binary interface for how operating system functions are called, and it will also define a file format for executables, but it will also provide an API, in the sense of providing a catalog of functions that can be called by an application to invoke OS services.

I think the diagram is just trying to emphasize that operating system functions are usually invoked through a different mechanism than a simple library call. Most of the common OS use processor interrupts to access OS functions. Typical modern operating systems are not going to let a user program directly access any hardware. If you want to write a character to the console, you are going to have to ask the OS to do it for you. The system call used to write to the console will vary from OS to OS, so right there is one example of why software is OS specific.

printf is a function from the C run time library and in a typical implementation is a fairly complex function. If you google you can find the source for several versions online. See this page for a guided tour of one. Down in the grass though it ends up making one or more system calls, and each of those system calls is specific to the host operating system.

Title: Why is software OS specific?

Body:
I'm trying to determine the technical details of why software produced using programming languages for certain operating systems only work with them.

It is my understanding that binaries are specific to certain processors due to the processor specific machine language they understand and the differing instruction sets between different processors. But where does the operating system specificity come from?
I used to assume it was APIs provided by the OS but then I saw this diagram in a book:

Operating Systems - Internals and Design Principles 7th ed - W. Stallings (Pearson, 2012)

As you can see, APIs are not indicated as a part of the operating system.

If for example I build a simple program in C using the following code:

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

main()
{
    printf("Hello World");

}
</code>```

Is the compiler doing anything OS specific when compiling this?


答:
There are a number of reasons, but one very important reason is that the Operating System has to know how to read the series of bytes that make up your program into memory, find the libraries that go with that program and load them into memory, and then start executing your program code. In order to do this, the creators of the OS create a particular format for that series of bytes so that the OS code knows where to look for the various parts of the structure of your program. Because the major Operating Systems have different authors, these formats often have little to do with each other. In particular, the Windows executable format has little in common with the ELF format most Unix variants use. So all this loading, dynamic linking and executing code has to be OS specific.

Next, each OS provides a different set of libraries for talking to the hardware layer.  These are the APIs you mention, and they are generally libraries that present a simpler interface to the developer while translating it to more complex, more specific calls into the depths of the OS itself, these calls often being undocumented or secured. This layer is often quite grey, with newer "OS" APIs are built partially or entirely on older APIs. For example, in Windows, many of the newer APIs Microsoft has created over the years are essentially layers on top of the original Win32 APIs.

An issue that does not arise in your example, but that is one of the bigger ones that developers face is the interface with the window manager, to present a GUI. Whether the window manager is part of the "OS" sometimes depends on your point of view, as well as the OS itself, with the GUI in Windows being integrated with the OS at a deeper level, while the GUIs on Linux and OS X being more directly separated. This is very important because today what people typically call "The Operating System" is a much bigger beast than what textbooks tend to describe, as it includes many, many application level components.

Finally, not strictly an OS issue, but an important one in executable file generation is that different machines have different assembly language targets, and so the actual generated object code must different. This isn't strictly speaking an "OS" issue but rather a hardware issue, but does mean that you will need different builds for different hardware platforms.

Title: Why is software OS specific?


答: Software is not always OS specific. Both Java and the earlier p-code system (and even ScummVM) allow for software that is portable across Operating Systems. Infocom (makers of Zork and the Z-machine), also had a relational database based on another virtual machine. However, at some level something has to translate even those abstractions into actual instructions to be executed on a computer.</p>

Title: Why is software OS specific?


问:
Calculate reachability of one point from another
I have an array which stores a set of positive x coordinates  in sorted way,
say  arr={1, 4, 5, 9, 12, 45} etc.

And I have a maximum distance k which I can go from one point to another point let k=3.
Now, given two points x and y(arr[x]<arr[y]) I need to determine if I can reach from x to y. I will be able to reach y from x if distance between every two hop is less that or equal to k.

Here suppose x=1  y=4 then I can go from 1->2 then 2->3 but since distance between 3 and 4 is greater than 3 I can't go so in this case I can't reach.

But if x=1 and y=2 then I can reach.

It can be simply solved with O(n). I have created a for loop from arr[x] to arr[y] and for each pair of points I check if distance between them is less than or equal to k.

But I want better algorithm. I am thinking of doing something like binary search. Can anybody please suggest a good algorithm?

答:
Lo0oks easy enough to do O(1) if you precompute all the answers.

Generate a 2D array of maximum differences, such that maxdiff[x,y] = max(diff[x], diff[x+1]...diff[y]). Since x

Note that maxdiff(x,y) = max(maxdiff(x,z), maxdiff(z,y)), so calculation of longer sequences reuses the work done on shorter ones. Build shortest paths first, then next shortest and so on.

Result is true if maxdiff[x,y] <= k.

For a practical implementation I would memoise this. That is, calculate the results as needed and keep the result until it is needed again. Once you have built all the maxdiffs for x..y you have built all the shorter distances in between for later use.

This is a typical space-speed trade-off.

I believe this algorithm is O(nlogn) for a single value of (x,y,k), dropping asymptotically towards O(n) for a large input data set or if the same (x,y,k) occur frequently.

If the array is large it may be impractical to build the entire lookup table, but a combination of memoisation and a partially built table will still deliver returns for large input data sets.


问:
Split work item into prototype and main work item?
During grooming, we usually have work items which get approved based upon the team understanding that what needs to be done? The product owner does not discuss the details of how it will be done and stops the discussion if team tries so. This applies to all work items (new UI, new API or changes to existing UI/API). Product Owner's reasoning is that getting into the details (both technical & functional) of how it will be done is something that needs to happen during sprint and discussing it during grooming is not correct. The effort estimation also happens based upon this discussion.

But during sprint planning, approved items are taken for the sprint and expectation is that if work item is approved, team should know all the details of the solution and should be able to complete the item in sprint. What happens is team spends first 2-3 days in doing the research and getting the PO's approval for the solution (UI design, key business logic clarification). Unless the analysis results in great difference in effort estimate, team is asked to complete the feature. This happens in each sprint.

I dont have a problem with putting extra effort in completing the work item. My question is regarding the process.

Should the team say no in approving the item unless team understands how the solution will look like?

Should the work item be splitted into research/analysis in which solution prototype will be proposed to the PO? Once the PO will approve the prototype, the main work item will be marked approved.

Any other suggestion as to how it can be handled in better way?

答:
The level of detail at the planning meeting depends a lot on the personality and expertise of the PO.

Take user interface as an example: Some product owners have strong UX skills or use UX experts outside the team. These PO's better come with a rough UX spec to the planning meeting. In other cases this skill is more present inside the team. Those teams handle the UX design as part of the implementation. The problem arises if the PO has strong opinions about the UI, but fails to communicate in advance what he wants. That is unfair towards the team.

In short, if it affects the acceptance of a work item, then the PO should not avoid the question at planning meeting.

On the other hand, you can't expect him to have all the answers prepared, the team must also think actively and give him some options to choose from.

One good way to approach this at the planning meeting, is to formulate questions to the PO as "would you accept the story if ...".

Back to your questions:

Should the team say no in approving the item unless team understands how the solution will look like?

Yes, if the PO is unable to give clarity on what he will accept and what not.

Should the work item be splitted into research/analysis in which solution prototype will be proposed to the PO? Once the PO will approve the prototype, the main work item will be marked approved.

If for a certain work item, you all feel an iterative approach would be best ("let's see how this works, and then decide if it needs a change"). Then it is better to split it into two items. But don't think of step 1 as a prototype, make it "potentially shippable" based on current understanding of the team and PO. The PO can always define work items to improve it later.

Any other suggestion as to how it can be handled in better way?

Some teams or PO's will prepare rough UX specs (wireframe) before the planning meeting: Aim for early failure. Just enough to agree on. So that when the team commits to a work item, the scope has been clarified in advance.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

Body:
Being forced to add a file description in each file (it's a C# project).

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="User.cs" company="Company">
//   Copyright (C) 2009 Company. All rights reserved.
// </copyright>
// <summary>
//   The user.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


问:
Charles Barkley syndrome
Charles Barkley was an excellent basketball player, a hall of fame, and a dream team member.  He played for the 76ers, Suns, and Rockets.  Yet he never won an NBA championship.  Some might argue this was because he was never surrounded by other players of his caliber, and in the NBA, you can't win on your own.

So what does this have to do with programming?

How many of you out there feel like Sir Charles?  Leading your team in every category, KLOCs, bugs fixed, systems configured...  Always the one pushing for improvements, upgrading systems, negotiating with customers...  Feeling like you are carrying the team.  Anger just under the surface.

Only to retire eventually, without "the ring"1.

1: Keep in mind, Charles never blamed his team.  He just performed at his best.

答:
Developers come in three flavors ... Einstein, Elvis and Mort. You know the Einsteins ... it might be you based on your question.  You know the Elvis ... he's all over twitter, posting blogs, trying to get famous from being a developer.  And, you know the Mort ... he shows up at 9:00 a.m. does a decent job and wants to go home at 5:00 p.m.  When you're Einstein, it can be very challenging dealing with Mort.

Mythical Man Month cites a study that indicates there is as wide as a 10:1 ratio between good developers and average developers ...

Within just this group the ratios between best and worst performances averaged about 10:1 on productivity measurements and an amazing 5:1 on program speed and space measurements!

It's just a fact of life in our industry that there is going to be a large disparity between the average and star performers.  To continue your metaphor, have you ever seen a pro basketball player playing against non-pros?  It's like that.

The best thing you can do for yourself is to recognize it and embrace it. Get into Mort's head, understand him, understand what he will do and what he will not do and use it.  Be patient with Mort, teach him, teach him again, explain it, explain it again.  It's all you can do.  At the end of the day, you will probably leave your company and wind up at a Microsoft or Google or somewhere where Einsteins (and Elvi) are appreciated.

ContentLicense: CC BY-SA 2.5

Title: Charles Barkley syndrome


问:
What are proven advantages of tools like GWT over pure JavaScript frameworks?
GWT is a software stack that translates Java code and a sub-set of the Java Runtime's class library to JavaScript code.

In comparison with JavaScript toolkits, GWT can seem alienating, by nature and by usage, and overly complex to do even simple things, taking away much of the fine-grained control you'd have by using JavaScript directly.

Why would a web-developer choose to use a tool like GWT, which uses a language originally not targeted for the web, instead of using pure JavaScript and JavaScript frameworks and toolkits?

Is it measurably better, and based on what criteria?

答:
Few benefits of using GWT that I think of ( more details read my blog http://www.pandurangpatil.com/2012/09/benefits-of-using-gwt.html)

As GWT client application is written in Java, one get an opportunity to catch syntactical mistakes at compile time because of the same (Though it doesn't support all the JRE classes as those features are not supported by the browsers itself). Lets take an example to understand what I am saying. If you misspell a JavaScript variable name by using pure JavaScript library. The only way you can catch such mistake is to run the application and test for desired results.
Java features like Generics and Annotations are use full and can be used in your application.

One can make use of existing available libraries or write one to generate code as per requirement with ease as the code that need to be generated need to be in Java. GWT compiler takes care of compiling it and converting it in to JavaScript.

Management of code becomes more easier.

One can simply write some common business logic in a such way that it can be used in GWT client side code and also on server side code as its in Java e.g. validation of data or some common utility functions.

With the use of GWT eclipse plug-in, you can easily debug the client code in Java for your business logic.

As GWT compiler compiles your client Java code and generates JavaScript out of it. Which you need deploy it to your server, and it gets served and executed in user browser when requested. While generating this JavaScript it will do some optimisations.

It doesn't consider dead code while generating JavaScript, when I say dead code I mean to say "code which is there but not getting called from main flow". In turn reduces the effective size of your final JavaScript code.

It takes care of obfuscating generated JavaScript code.

It does minification of generated JavaScript code.

And more importantly it will generate browser specific optimised code separately. When I say separately, it will generate browser specific separate JavaScript which will be served when respective request is received from given browser. Which in turn reduces the size of the JavaScript code which gets downloaded for specific browser as it doesn't contain all browser specific handling in one single code.

If you are writing your application for different languages i.e. English, Hindi, Marathi etc by using Internationalisation feature of GWT. While generating JavaScript code it creates copy per language and browser combination. Which makes generated JavaScript code for given combination of language and browser most optimal and small one.

In case you need to use direct JavaScript which can be called from Java GWT code one can do it using JSNI ( JavaScript Native Interface). One can even call GWT Java Code back from JavaSctipt.

If you want to make Bookmark able pages then you can make use of History feature of GWT.

If you want to make use of JSON as data format for communication and manipulation it has very good feature called JavaScript Overlay Types.

Deferred Binding feature of GWT is a good feature which I suppose is possible to provide because of Java.

You can build your user interface using available widgets of GWT in Java Swing style. You can even create your custom widgets very easily.

If you want to build your user interface ( Web pages ) in pure html style, you can make use of Declarative UI feature of GWT. Which I feel one of the major feature of GWT. Which makes it easier for developer to build pages in pure HTML style. Which I suppose is more maintainable than Swing style coding. And most importantly you can still have your logic in Java and only presentation part in pure HTML. (Note: which ever method you use (Declarative UI or Swing Style) ultimately its going to be HTML only but what makes difference is the way you code and maintain it).

Client Bundle feature of GWT makes it very easy to manage your other web resources like css, images and other text contents.

CSS resources makes it possible to have conditional logic inside your css. You can also access some dynamic values from your GWT client side Java code.

It will also take care of obfuscating your css classes. And most importantly GWT has automated generation of interfaces from your css files to use css classe's.

Image resource makes it easier for developer to use images in your application in very easily maintainable fashion. When I say easily I mean to say when you want to use images in GWT Java code rather than using hard coded URL, you can use image resource. Benefit you will get using image resource is if you are going to change the location or use some different image with different name you just need to change it at one location. More important feature of image resource is when you use it with CSS resource as sprite. It will take care of making that image as in-line data uri or use it with sprite. I don't say its not possible to do it with other frameworks what's more important is how fast and easily you can do it. GWT makes it much easier for you.

Data Resource add some optimisation for data files like .pdf to rename those files based on their contents to make it strongly cacheable by browser. Small data files may be converted in to in-line data uri.

By making use of Client Bundle for other web resources and if you properly structure you application into different modules. It can become completely reusable modules as whole with every resource. What's the big deal about reusable modules? well if you are using images by using direct URL in some module. And if you include that module in other module and try to use the components created in that module you still need to have those images copied to public URL of your final application. Which you don't have to do it if you use those images as image resources.

Other optimisation you can achieve by creating small modules by using client bundle for css and images. Where you can chose to include only required modules inside your final module/s. The difference it will make is final module JavaScript and other resources will only contain required contents and not the whole contents even if you want to use small piece of the module.

Cell Widgets: To present paginated data collection GWT has Cell Widgets. There are widgets like CellTable, CellList, CellTree and CellBrowser.

CellTable is meant for presenting data in paginated table format, it has feature where in you can change the contents of given cell in place. It supports pagination on client side  and server side both, it support sorting on column and also it supports selection of one or multiple records and generating events for the same.

CellList can be used to present data in list format and items can displayed in custom format. It also supports client and server side pagination and selection of one or multiple records and generates events for selection.
CellTree and CellBrowser can be used to present data in tree format.

Communication with server from GWT client code. It supports multiple ways to implement client server communication.

If you are not concerned about the protocol being used for data transfer then it GWT RPC mechanism. Its very easy to integrate your client side code for data transfer with server. You can define custom DTO's (data transfer object) in client code which can be even used on server side code. Server side implementation accepts the same DTO's as parameter or return value. Everything else is taken care by GWT RPC frame work. It even propagates exceptions raised from server side code to caller in client side code (Provided you need to define those Exception classes inside client side code package. GWT RPC internally makes use of AJAX calls with their own custom protocol for data transfer.

If you don't want to use GWT RPC you can make server AJAX calls to fetch data from server using Request Builder. Which is also much easier to implement.
It also has interesting feature Request Factory. With this feature you can make your DAO or Service layer exposed to get called from client code. To do that you need define few set of interfaces for your service and custom data types. And using these interfaces you can access those services from client code. I have written maven plugin to generate these interface. If you annotate your DAO layer with some required annotations refer (https://github.com/pandurangpatil/gwt-mvn-helper) refer mvn-helper-test module inside it for usage. Request Factory is more targeted to integrate with ORM layer like JDO or JPA on server. It has a support to call persist on given entity from client code. And most important when you call persist method it compute and send only change (delta) to server to save.

If you want to make cross domain JSONP call you can do the same refer.


答:
Another way of doing it, is by splitting the session into two parts.

In the first one the Product Owner goes into the level of detail that the team needs in order to understand the requirements. No effort estimation will be done during this part. Then the PO leaves the room and the team starts with the estimation process the includes the "how it will be done".

The PO should be be available to answer questions that will come up. This is an important part of the sprint planning where you can include planning poker or any other estimation techniques. It is important that the planning will not take forever and you should have an end time where you close the session.

Anything that the team considers important should be discussed during the planning session. It is good practice. If the team leaves the room and have lots of questions it's impossible be productive. In case there are too many unknown factors then you could start a spike to research a concept and/or create a simple prototype. But it should be the exception and not the rule.

Title: Split work item into prototype and main work item?

Body:
During grooming, we usually have work items which get approved based upon the team understanding that what needs to be done? The product owner does not discuss the details of how it will be done and stops the discussion if team tries so. This applies to all work items (new UI, new API or changes to existing UI/API). Product Owner's reasoning is that getting into the details (both technical & functional) of how it will be done is something that needs to happen during sprint and discussing it during grooming is not correct. The effort estimation also happens based upon this discussion.

But during sprint planning, approved items are taken for the sprint and expectation is that if work item is approved, team should know all the details of the solution and should be able to complete the item in sprint. What happens is team spends first 2-3 days in doing the research and getting the PO's approval for the solution (UI design, key business logic clarification). Unless the analysis results in great difference in effort estimate, team is asked to complete the feature. This happens in each sprint.

I dont have a problem with putting extra effort in completing the work item. My question is regarding the process.

Should the team say no in approving the item unless team understands how the solution will look like?

Should the work item be splitted into research/analysis in which solution prototype will be proposed to the PO? Once the PO will approve the prototype, the main work item will be marked approved.

Any other suggestion as to how it can be handled in better way?


答:
Should the team say no in approving the item unless team understands how the solution will look like?

No, of course not. Not knowing the implementation details leaves the team leeway in finding the simplest solution later on. This doesn't mean that discussion should be prevented, but it should certainly be limited.

Suppose for example that in the planning meeting it is decided to play a story in a certain way. Should the team be forced to use that design during the sprint? That is contrary to the agile manifesto.

Should the work item be splitted into research/analysis in which solution prototype will be proposed to the PO? Once the PO will approve the prototype, the main work item will be marked approved.

No, this won't help the team, because prototypes have no value for your users, and therefore should have the lowest priority according to Scrum. You should only do prototypes if needed once you commit to the story, not before.

Any other suggestion as to how it can be handled in better way?

I have a few:

Why is your product owner acting a Scrum Master? The roles should really be separate, and doing otherwise is generally a Bad Idea™

Why are you estimating your stories two times? This should not really happen. You estimate them once, imprecisely, to get an idea of what fits in a sprint. No one should care beyond that point -- the measure becomes what you actually accomplish. Of course, there can be task estimates, but they are purposefully in a separate set of units because they should never be used to estimate what fits in a sprint, but only how much work is left.

You seem to have a problem in collaborating with the PO during the sprint. For example you say the "team struggles during first 2-3 days in doing the research and getting the PO's approval for the solution". This makes no sense to me. The PO should be concerned with the end result for the user and not committed to a particular solution. They get to specify some end-to-end acceptance tests before hand, but everything that passes them is fair game -- anything else should be a new story.

Your suggestion of having a prototype->story pipeline goes against collaboration and towards a separation of roles. What you really need, instead is to have PO and team collaborate during the whole sprint and talk to each other. The stories should not be designed until they are done. What you call a "prototype" should really be the story.


问:
Why do some functional programming languages use a space for function application?
Having looked at some languages for functional programming, I always wondered why some fp-languages use one or more whitespace characters for function application (and definition), whereas most (all?) imperative/object-oriented languages are using parentheses, which seems to be the more mathematical way. I also think that the latter style is much more clear and readable than without the parens.

So if we have a function f(x) = x² there are the two alternatives to calling it:

FP: f x

Examples:

ML, Ocaml, F#

Haskell

LISP, Scheme (somehow)

Non-FP: f(x)

Examples:

Almost all imperative languages (I know, see the comments/answers)

Erlang

Scala (also allows "operator notation" for single arguments)

What are the reasons for "leaving out" the parentheses?

答:
which seems to be the more mathematical way

functional languages are inspired by lambda calculus. In this field, parentheses are not used for function application.

I also think that the latter style is much more clear and readable than without the parens.

Readability is in the eye of the beholder. You are not used to reading it. It is a bit like mathematical operators. If you understand the associativity, you only need a few parens to clarify the structure of your expression. Often you don't need them.

Currying is also a good reason to use this convention. In haskell, you can define the following:

```<code>add :: Int -> Int -> Int
add x y = x + y

x = add 5 6 -- x == 11
f = add 5
y = f 6 -- y == 11
z = ((add 5) 6) -- explicit parentheses; z == 11
</code>```

With parens, you could use two convention: f(5, 6) (not curried) or f(5)(6) (curried). The haskell syntax helps to get used to the currying concept. You can still use a non-curried version, but it is more painful to use it with combinators

```<code>add' :: (Int, Int) -> Int
add' (x, y) = x + y
u = add'(5, 6) -- just like other languages
l = [1, 2, 3]
l1 = map (add 5) l -- [6, 7, 8]
l2 = map (\x -> add'(5, x)) l -- like other languages
</code>```

Notice how the second version forces you to register x as a variable, and that the subexpression is a function which takes an integer and adds 5 to it? The curried version is much lighter, but also considered by many as more readable.

Haskell programs makes extensive use of partial application and combinators as a mean of defining and composing abstractions, so this is not a toy example. A good function interface will be one where the order of parameters provides a friendly curried usage.

Another point: a function without parameters should be called with f(). In haskell, since you only manipulate immutable lazy evaluated values, you just write f, and consider it as a value which will need to perform some computations when needed. Since its evaluation won't have any side effect, it makes no sense to have a different notation for the parameterless function and its returned value.

There are also other conventions for function application:

Lisp: (f x) -- prefix with external parentheses

Forth: x f -- postfix

Body:
which seems to be the more mathematical way

functional languages are inspired by lambda calculus. In this field, parentheses are not used for function application.

I also think that the latter style is much more clear and readable than without the parens.

Readability is in the eye of the beholder. You are not used to reading it. It is a bit like mathematical operators. If you understand the associativity, you only need a few parens to clarify the structure of your expression. Often you don't need them.

Currying is also a good reason to use this convention. In haskell, you can define the following:

add :: Int -> Int -> Int
add x y = x + y

x = add 5 6 -- x == 11
f = add 5
y = f 6 -- y == 11
z = ((add 5) 6) -- explicit parentheses; z == 11

With parens, you could use two convention: f(5, 6) (not curried) or f(5)(6) (curried). The haskell syntax helps to get used to the currying concept. You can still use a non-curried version, but it is more painful to use it with combinators

add' :: (Int, Int) -> Int
add' (x, y) = x + y
u = add'(5, 6) -- just like other languages
l = [1, 2, 3]
l1 = map (add 5) l -- [6, 7, 8]
l2 = map (\x -> add'(5, x)) l -- like other languages

Notice how the second version forces you to register x as a variable, and that the subexpression is a function which takes an integer and adds 5 to it? The curried version is much lighter, but also considered by many as more readable.

Haskell programs makes extensive use of partial application and combinators as a mean of defining and composing abstractions, so this is not a toy example. A good function interface will be one where the order of parameters provides a friendly curried usage.

Another point: a function without parameters should be called with f(). In haskell, since you only manipulate immutable lazy evaluated values, you just write f, and consider it as a value which will need to perform some computations when needed. Since its evaluation won't have any side effect, it makes no sense to have a different notation for the parameterless function and its returned value.

There are also other conventions for function application:

Lisp: (f x) -- prefix with external parentheses

Forth: x f -- postfix


问:
Multilayered enterprise application use of JAXB objects
I am asked to refactor and maintain an enterprise application. Normally I'm used to using the MVC design pattern. This time however, I'd like to separate everything into layers (multilayered architecture).
Something along the lines of (Microsoft Application Architecture Guide, 2nd Edition - October 2009):

My data sources are in general XML files. These files are read and written with the use of JAXB, and this resides in the data-layer. Whenever I load a specific XML a "provider" will use JAXB to construct a tree of objects representing the XML structure. These objects/information needs to be used inside the business, service and presentation layer. Per layer the information needs to be treat differently, i.e. business layer will enforce business rules on the objects/information whereas the presentation layer needs additional UI information to have everything shown to the user.

I'm looking for your tips / experiences when it comes down to using data sources throughout an multilayered application.
Should I:

Create some sort of mapping, such that a new object tree is constructed in every layer?

Work via the lines of aggregation, such that my data sources can be decorated with extra functionality / information inside an object that lives in another layer?

Make the JAXB-objects "fat", with an interface which supports all my needs that come from all other layers?

I'd love to hear your thoughts!

答:
I would recommend the following:

Implement the data layer using an established ORM framework. My favorite is myBatis, but JPA and Hibernate are definite contenders.

Wrap the data layer with a Java API that supports only business operations (not CRUD operations)- e.g. Read customer details, enrol new customer, cancel customer, place order etc. That way you are free to decide in the data layer if you need to record history, do transaction logging etc. It also has the advantage that heavy operations (e.g. Batch jobs) can use the API direct, while enterprise-wide operations use SOAP or similar. The important point is that all clients end up using the same API.

If your data layer is well designed, the business layer should be almost a pass-through. If not, you are probably on the road to ruin, as your database does not reflect how you do business.

MVC is great for the GUI layer, but in my view has limited application elsewhere. If you get it right, the model layer will consist simply of an aggregation of some of your DAO POJOs. View will be JSPs, JSF or some other established technology. I like to use Spring Web MVC with JSPs, but there are lots of alternatives.

External system mapping should be flexible, allowing you to map from someone elses view of reality to your own internal enterprise data model. Standardised protocols like SOAP win here, but there seems to be a move to REST interfaces, which don't yet have the same level of definition.

In any case, there is more than one "correct" answer. there is a long-standing joke that if you ask three software architects for an opinion, you will get at least 4 answers...


问:
What defines the dimensionality of an array?
I know that when we speak about an array having 1, 2, or 4 dimensions, we mean arrays like this:

```<code>1: [0]
2: [0,0]
3: [0,0,0]
4: [0,0,0,0]
...
</code>```

Is the first 'axis' of an array the only thing that defines its dimensionality?  Can an array with 4 dimensions be represented these ways?

```<code>[0, [0,0,0]]
[[0,0], [0,0]]
</code>```

or does this fall under some other definition of dimensionality?

Another option is that a 4-dimensional array would be of the form

```<code>[ [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]] ]
</code>```

e.g.

```<code>[
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ]
]
</code>```

Is this just a nomenclature nuance that I'm bringing up?  Is this definition relative to the field in which we are discussing (computation vs. physical systems)?

(the thoughts came from this question.)

答:
An n-dimensional array is a collection of data.
This data can be accessed by a value.

People often associate this value with coordinate in an n-dimensional space so this value would have n components say (x,y,z) for 3-d array.
In other words, the number of dimensions in an array is the number of components in the value you use to access data in the array.

Now comes the thing that few people already mentioned in their answer which is they say array is not the same as tree hierarchy. This is because we can all sense that there is something difference between a tree and a cube other than notation but many can't say what the difference is. After all, data in a tree and data in an n-dimension array can be identified by a vector like value.

I am surprised that nobody has spotted the difference yet. It is simple and trivial. The difference is in the way they grow. Tree grows in depth, which means their branching factor stays the same. On the other hand, cube (array) grows in length which means their depth stays the same (same number of dimension) but the branching factor changes if you see them from tree like perspective. This results in one having exp grow and minimum compression, while there is the opposite for the other. From a computer software viewpoint, you can see the difference in the way you declare a variable.


问:
Why isn't there a next operation on enums?
In most popular programming languages like Java and C# there is a way to define enums, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek.

The problem is, given a value, e.g. DayOfWeek.Monday, how do I get the next value of the enum, in this particular case DayOfWeek.Tuesday?

I realize that not all enums are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next operation would be sufficient in most cases. In fact, since the set of values in a enum is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.

So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next value for a enum? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.

I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place.

答:
Speaking for Java, what you are actually looking for is Enumeration (which is more like iterator) which has the nextElement support.

enum is a data type which allows variable to have a set of predefined values.


答:
Parenthesis for function application is just one of the many saddles Euler left us with. Like anything else mathematics needs conventions when there are several ways to do something. If your mathematical education only extends as far as a non-maths subject at university then you probably aren't too familiar with the many fields where function application happens happily without any of these nonsense brackets (e.g. Differential Geometry, Abstract Algebra). And you don't even mention functions that are applied infix (almost all languages), "outfix" like taking a norm, or diagrammatically (Befunge, Algebraic Topology).

So in answer I'd say it's due to a much higher proportion of functional programmers and language designers having extensive mathematical education. Von Neumann says "Young man, in mathematics you don't understand things. You just get used to them.", certainly this is true of notation.

Title: Why do some functional programming languages use a space for function application?

Body:
Having looked at some languages for functional programming, I always wondered why some fp-languages use one or more whitespace characters for function application (and definition), whereas most (all?) imperative/object-oriented languages are using parentheses, which seems to be the more mathematical way. I also think that the latter style is much more clear and readable than without the parens.

So if we have a function f(x) = x² there are the two alternatives to calling it:

FP: f x

Examples:

ML, Ocaml, F#

Haskell

LISP, Scheme (somehow)

Non-FP: f(x)

Examples:

Almost all imperative languages (I know, see the comments/answers)

Erlang

Scala (also allows "operator notation" for single arguments)

What are the reasons for "leaving out" the parentheses?


答:
It is because of the nature of enums (enum in Java), (enum in C#). They are just fixed constants in the language, holding essential data (sometimes just their own names or just identity), not a kind of list. Therefore if you need this kind of logic (which might be applicable to many cases), then you actually have to create the logic.

Apart of being some sort of linked list, it can be singleton too (see: Implementation Example: Using enum). It is more matter of use. Sadly enums (at least in Java) in this way tricker since you can't extend them or define an interface directly for them.

It is an open debate if it is good practice or not to use enums for some sort of constant list or singleton, the fact is, you can. I would vote against using it unless it is widely used pattern in the project. Smells like hacking for me if it is used locally.

Title: Why isn't there a next operation on enums?

Body:
In most popular programming languages like Java and C# there is a way to define enums, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek.

The problem is, given a value, e.g. DayOfWeek.Monday, how do I get the next value of the enum, in this particular case DayOfWeek.Tuesday?

I realize that not all enums are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next operation would be sufficient in most cases. In fact, since the set of values in a enum is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.

So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next value for a enum? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.

I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place.


问:
Databases and the single responsibility principle
Can the single responsibility principle be applied to databases? relational databases I mean.

I'm asking this because a typical database will have several tables and we may find something like that between them:

Tables handle ACL and permissions.

Tables handle user authentication.

Tables relating to cron jobs and scheduled tasks.

Tables relating to the domain itself.

Tables relating to emails and invitations and so on.

Look ups.

Moreover the tables relating to the domain might be divided according to the application module they back up.

In code we usually divide our code base to modules/packages/namespaces, but that concept is absent from relational databases as far as I know.

so what I'm asking should the database be divided somehow to smaller databases? or maybe database (modules?!) Or should we just lump everything together and hope  for a good naming convention if any?!

答:
The SRP applies to the classes and methods you define. A database is not a user-defined entity, it is a piece of infrastructure that transcends individual requirements and responsibilities (in fact, it is better having to deal with only one database for a system than having to juggle multiple ones).

Therefore, there is no point worrying about the fact that completely different pieces of functionality map to relations (tables) in the same data base. If you want to enforce the SRP, focus on getting each relation to serve a clearly-defined purpose, not the entire DB.


答:
Why isn't there a next operation on enums?

It is difficult to generalize.

It is an decision made by each programming language designer / team.  But note that some programming languages do provide a "next" operation for enumerated types.

In Pascal, the succ function returns the next value of an enumerated type, and the pred function returns the previous value.  But this only works for classic enumerated types.  C-style enumerated types have "holes" in the type domain, and the succ and pred functions are not allowed.

Reference: http://www.freepascal.org/docs-html/ref/refse12.html#QQ2-27-32

And, in fact, that gives a clue as to why many languages with enumeration / enumerated types don't have a "next" operation.  It is prohibitively expensive when you can't implement "next" by using integer addition under the hood.

Of course, in the languages that don't support next directly, it is always possible to implement it for yourself ... if you need it ... as some kind of helper method / function.


问:
Reduce a list of IPv4 to lowest common CIDR
I have a long list of IP addresses that show some pattern of closeness

Example:

```<code>XX.249.91.16
XX.249.91.21
XX.249.91.32
XX.249.91.160
XX.249.91.165
XX.249.92.15
XX.249.92.25
XX.249.92.51
XX.249.92.234
</code>```

and sometimes a whois reveals a range like this

```<code>XX.163.224.0 - XX.163.239.255
</code>```

I would like to create a list of CIDR that gives me the lowest common number

It seems Python already has such a thing - iprange_to_cidrs - but I need it in JavaScript

```<code>XX.249.90.0/16
</code>```

if that is what would handle

```<code>XX.249.91.0 - XX.249.92.255
</code>```

ditto  XX.163.200.0/nn to handle

```<code>XX.163.224.0 - XX.163.239.255
</code>```

A calculator that can do it one range at a time when I fiddle with the mask is here
http://www.subnet-calculator.com/cidr.php

My preferred language is JavaScript and I have the following start but need the algorithm that does the match and transform

```<code>var list = [
    "10.249.91.16",
    "10.249.91.21",
    "10.249.91.32",
    "10.249.91.160",
    "10.249.91.165",
    "10.249.92.15",
    "10.249.92.25",
    "10.249.92.51",
    "10.249.92.234"
]
function dec2bin(ip) {
    return ip.map(function(num) {
      return ("00000000"+parseInt(num,10).toString(2)).slice(-8);
    }).join(".");
}
const result = list.map(ip => dec2bin(ip));
</code>```

UPDATE after reviewing an answer

FIDDLE

```<code>const getDec = ip => {
  let octet = ip.split(".");
  return (octet[0] << 24) | (octet[1] << 16) | (octet[2] << 8) | octet[3];
};

var adr1 = "111.163.224.0";
var adr2 = "111.163.239.255"
var XOR = getDec(adr1)^getDec(adr2);

// now what?
</code>```

Update 2:

could the result of the range 111.163.224.0 - 111.163.239.255 be 111.163.224.0/20 ? since we have

```<code>01101111.10100011.11100000.00000000 - 0,111.163.224.0
01101111.10100011.11101111.11111111 - 0,111.163.239.255
</code>```

答:
I have updated the solution which gave negative ints when using addresses with 255

fiddle

```<code>const dot2dec = ip => {
  const octet = ip.split(".");
  return (octet[0] * 16777216) + (octet[1] * 65536) + (octet[2] * 256) + (octet[3] * 1);
};

const num2dot = num => {
  let d = num % 256;
  num = Math.floor(num / 256);
  let c = num % 256;
  num = Math.floor(num / 256);
  let b = num % 256;
  num = Math.floor(num / 256);
  let a = num % 256;
  return a + "." + b + "." + c + "." + d;
};

const dec2bin = ip =>
  ip
  .split(".")
  .map(num => ("00000000" + parseInt(num, 10).toString(2)).slice(-8))
  .join(".");

const fixNegativeResult = result => result < 0 ? result >>> 0 : result;

$(function() {
  const res1 = $("#res1");
  const adr1 = "255.255.255.0";
  const adr2 = "255.255.255.123";
  //const adr1 = "111.163.224.0";
  //const adr2 = "111.163.239.255"
  res1.append("<hr>" + dot2dec(adr1) + " - " + adr1);
  res1.append("<hr>" + dot2dec(adr2) + " - " + adr2);

  const dec1 = dot2dec(adr1);
  const dec2 = dot2dec(adr2);
  const XOR = num2dot(dec1 ^ dec2);

  const andResult = fixNegativeResult(dec1 & dec2);
  const AND = num2dot(andResult);

  const MASK = dec2bin(XOR).replace(/\./g, "").indexOf("1");

  res1.append("<hr>XOR:" + XOR);
  res1.append("<hr>AND:" + AND);
  res1.append("<hr>MASK:" + MASK + "<hr>");
});
</code>```

Old solition

Solution was simpler than expected. I appreciate Blrfl's time and explanation but the whole thing boiled down to the number to use is the two addresses ANDed masked by the number of leading 0s in the binary representation of the two addresses XORed

Fiddle

```<code>var adr1 = "111.163.224.0",
    adr2 = "111.163.239.255",
    AND  = dot2dec(adr1)&dot2dec(adr2),
    XOR  = num2dot(dot2dec(adr1)^dot2dec(adr2)),
    mask = dec2bin(XOR).replace(/\./g,"").indexOf("1");
</code>```

in this case 111.163.224.0/20

Body:
I have updated the solution which gave negative ints when using addresses with 255

fiddle

const dot2dec = ip => {
  const octet = ip.split(".");
  return (octet[0] * 16777216) + (octet[1] * 65536) + (octet[2] * 256) + (octet[3] * 1);
};

const num2dot = num => {
  let d = num % 256;
  num = Math.floor(num / 256);
  let c = num % 256;
  num = Math.floor(num / 256);
  let b = num % 256;
  num = Math.floor(num / 256);
  let a = num % 256;
  return a + "." + b + "." + c + "." + d;
};

const dec2bin = ip =>
  ip
  .split(".")
  .map(num => ("00000000" + parseInt(num, 10).toString(2)).slice(-8))
  .join(".");

const fixNegativeResult = result => result < 0 ? result >>> 0 : result;

$(function() {
  const res1 = $("#res1");
  const adr1 = "255.255.255.0";
  const adr2 = "255.255.255.123";
  //const adr1 = "111.163.224.0";
  //const adr2 = "111.163.239.255"
  res1.append("<hr>" + dot2dec(adr1) + " - " + adr1);
  res1.append("<hr>" + dot2dec(adr2) + " - " + adr2);

  const dec1 = dot2dec(adr1);
  const dec2 = dot2dec(adr2);
  const XOR = num2dot(dec1 ^ dec2);

  const andResult = fixNegativeResult(dec1 & dec2);
  const AND = num2dot(andResult);

  const MASK = dec2bin(XOR).replace(/\./g, "").indexOf("1");

  res1.append("<hr>XOR:" + XOR);
  res1.append("<hr>AND:" + AND);
  res1.append("<hr>MASK:" + MASK + "<hr>");
});

Old solition

Solution was simpler than expected. I appreciate Blrfl's time and explanation but the whole thing boiled down to the number to use is the two addresses ANDed masked by the number of leading 0s in the binary representation of the two addresses XORed

Fiddle

var adr1 = "111.163.224.0",
    adr2 = "111.163.239.255",
    AND  = dot2dec(adr1)&dot2dec(adr2),
    XOR  = num2dot(dot2dec(adr1)^dot2dec(adr2)),
    mask = dec2bin(XOR).replace(/\./g,"").indexOf("1");

in this case 111.163.224.0/20


答:
You mention on how if the code is specific to a CPU, why must it be specific also to an OS. This is actually more of an interesting question that many of the answers here have assumed.

CPU Security Model

The first program run on most CPU architectures runs inside what is called the inner ring or ring 0. How a specific CPU arch implements rings varies, but it stands that nearly every modern CPU has at least 2 modes of operation, one which is privileged and runs 'bare metal' code which can perform any legal operation the CPU can perform and the other is untrusted and runs protected code which can only perform a defined safe set of capabilities. Some CPUs have far higher granularity however and in order to use VMs securely at least 1 or 2 extra rings are needed (often labelled with negative numbers) however this is beyond the scope of this answer.

Where the OS comes in

Early single tasking OSes

In very early DOS and other early single tasking based systems all code was run in the inner ring, every program you ever ran had full power over the whole computer and could do literally anything if it misbehaved including erasing all your data or even doing hardware damage in a few extreme cases such as setting invalid display modes on very old display screens, worse, this could be caused by simply buggy code with no malice whatsoever.

This code was in fact largely OS agnostic, as long as you had a loader capable of loading the program into memory (pretty simple for early binary formats) and the code did not rely on any drivers, implementing all hardware access itself it should run under any OS as long as it is run in ring 0. Note, a very simple OS like this is usually called a monitor if it is simply used to run other programs and offers no additional functionality.

Modern multi tasking OSes

More modern operating systems including UNIX, versions of Windows starting with NT and various other now obscure OSes decided to improve on this situation, users wanted additional features such as multitasking so they could run more than one application at once and protection, so a bug (or malicious code) in an application could no longer cause unlimited damage to the machine and data.

This was done using the rings mentioned above, the OS would take the sole place running in ring 0 and applications would run in the outer untrusted rings, only able to perform a restricted set of operations which the OS allowed.

However this increased utility and protection came at a cost, programs now had to work with the OS to perform tasks they were not allowed to do themselves, they could no longer for example take direct control over the hard disk by accessing its memory and change arbitrary data, instead they had to ask the OS to perform these tasks for them so that it could check that they were allowed to perform the operation, not changing files that did not belong to them, it would also check that the operation was indeed valid and would not leave the hardware in an undefined state.

Each OS decided on a different implementation for these protections, partially based on the architecture the OS was designed for and partially based around the design and principles of the OS in question, UNIX for example put focus on machines being good for multi user use and focused the available features for this while windows was designed to be simpler, to run on slower hardware with a single user. The way user-space programs also talk to the OS is completely different on X86 as it would be on ARM or MIPS for example, forcing a multi-platform OS to make decisions based around the need to work on the hardware it is targeted for.

These OS specific interactions are usually called "system calls" and encompass how a user space program interacts with the hardware through the OS completely, they fundamentally differ based on the function of the OS and thus a program that does its work through system calls needs to be OS specific.

The Program Loader

In addition to system calls, each OS provides a different method to load a program from the secondary storage medium and into memory, in order to be loadable by a specific OS the program must contain a special header which describes to the OS how it may be loaded and run.

This header used to be simple enough that writing a loader for a different format was almost trivial, however with modern formats such as elf which support advanced features such as dynamic linking and weak declarations it is now near impossible for an OS to attempt to load binaries which were not designed for it, this means, even if there were not the system call incompatibilities it is immensely difficult to even place a program in ram in a way in which it can be run.

Libraries

Programs rarely use system calls directly however, they almost exclusively gain their functionality though libraries which wrap the system calls in a slightly friendlier format for the programming language, for example, C has the C Standard Library and glibc under Linux and similar and win32 libs under Windows NT and above, most other programming languages also have similar libraries which wrap system functionality in an appropriate way.

These libraries can to some degree even overcome the cross platform issues as described above, there are a range of libraries which are designed around providing a uniform platform to applications while internally managing calls to a wide range of OSes such as SDL, this means that though programs cannot be binary compatible, programs which use these libraries can have common source between platforms, making porting as simple as recompiling.

Exceptions to the Above

Despite all I have said here, there have been attempts to overcome the limitations of not being able to run programs on more than one operating system. Some good examples are the Wine project which has successfully emulated both the win32 program loader, binary format and system libraries allowing Windows programs to run on various UNIXes. There is also a compatibility layer allowing several BSD UNIX operating systems to run Linux software and of course Apple's own shim allowing one to run old MacOS software under MacOS X.

However these projects work through enormous levels of manual development effort. Depending on how different the two OSes are the difficulty ranges from a fairly small shim to near complete emulation of the other OS which is often more complex than writing an entire operating system in itself and so this is the exception and not the rule.

Title: Why is software OS specific?


答:
I think that the SRP translates directly to the principles of orthogonal design and full normalization in relational databases.

If you recollect that SRP states that there there should never be more than one reason for a class to change then the analogy becomes immediately apparent.

However, whether the database should be split into multiple smaller databases is an orthogonal issue, which is more of interest for pracical reasons then logical.

Title: Databases and the single responsibility principle

Body:
Can the single responsibility principle be applied to databases? relational databases I mean.

I'm asking this because a typical database will have several tables and we may find something like that between them:

Tables handle ACL and permissions.

Tables handle user authentication.

Tables relating to cron jobs and scheduled tasks.

Tables relating to the domain itself.

Tables relating to emails and invitations and so on.

Look ups.

Moreover the tables relating to the domain might be divided according to the application module they back up.

In code we usually divide our code base to modules/packages/namespaces, but that concept is absent from relational databases as far as I know.

so what I'm asking should the database be divided somehow to smaller databases? or maybe database (modules?!) Or should we just lump everything together and hope  for a good naming convention if any?!


问:
Design Patterns for Javascript
A lot of web frameworks have a MVC-style layout to code and approaching problems. What are some good similar paradigms for JavaScript? I'm already using a framework (jQuery) and unobtrusive js, but that still doesn't address the problem I run into when I have more complex web apps that require a lot of javascript, I tend to just end up with a bunch of functions in a single, or possibly a few files. What's a better way to approach this?</p>

答:
I'd recommend using namespacing and then a file structure that mirrors the namespace. For example, using Brad's answer, I'd have Truck.js, Car.js and Vehicle.js. This should give you a codebase that is easier to maintain, organise and unit test. However, you should have some kind of build process which concatenates and minfies your multiple JS files ready for production.

With an organised codebase of prototypal objects you should be in a position to implement most design patterns. There are also some good books on this subject. This presentation by Nicholas Zackas is also useful to get some insight in how to build good Javascript apps.

Also, in Javascript, I think its also important to distinguish between patterns and techniques. You need to be familiar with various commonly used techniques which JS natively lacks, such as namespacing. But these are techniques not patterns; techniques which make it easier to build patterns such as those defined by the Gang of Four.

Sorry this such a brief summary. But I'd strongly recommend the resources I mentioned to get greater insight.

Title: Design Patterns for Javascript


问:
Does the MIT license allow me to make a product that's a front-end for another MIT-license product?
I've been struggling with timezones online for a few years now. Because I've had enough of it,  I want to develop a Chrome extension that leverages moment.js so I can paste in a representation of a time and it will return the time in the user's current timezone. So this is basically a GUI front-end for moment.js. I would release this for free on the Chrome web store (and I'm surprised that such a Chrome extension does not exist yet).

Does the MIT license allow this?

答:
The MIT license is a very permissive license. You can do just about anything with software that is covered by the MIT license except for removing the copyright and license information.

So, yes you can create a GUI front-end for moment.js and you are not even restricted in your choice of license for the front-end.


答:
You say

software produced using programming languages for certain operating systems only work with them

But the program you give as an example will work on many operating systems, and even some bare-metal environments.

The important thing here is the distinction between the source code and the compiled binary. The C programming language is specifically designed to be OS independent in source form. It does this by leaving the interpretation of things like "print to the console" up to the implementer. But C may be complied to something which is OS specific (see other answers for reasons). For example, the PE or ELF executable formats.

Title: Why is software OS specific?


问:
Pointer indexing
I am currently reading a book titled "Numerical Recipes in C". In this book, the author details how certain algorithms inherently work better if we had indices starting with 1 (I don't entirely follow his argument and that isn't the point of this post), but C always indexes its arrays starting with 0. In order to get around this, he suggests simply decrementing the pointer after allocation, e.g.:

```<code>float *a = malloc(size);
a--;
</code>```

This, he says, will effectively give you a pointer that has an index starting with 1, which will then be free'd with:

```<code>free(a + 1);
</code>```

As far as I'm aware, though, this is undefined behavior by the C standard. This is apparently a highly reputable book within the HPC community, so I don't want to simply disregard what he's saying, but simply decrementing a pointer outside of the allocated range seems highly sketchy to me. Is this "allowed" behavior in C? I have tested it out using both gcc and icc, and both of those results appear to indicate that I'm worrying over nothing, but I want to be absolutely positive.

答:
You are right that code such as

```<code>float a = malloc(size);
a--;
</code>```

yields undefined behavior, per the ANSI C standard, section 3.3.6:

Unless both the pointer operand and the result point to a member of the same
  array object, or one past the last member of the array object, the behavior is undefined

For code like this, the quality of the C code in the book (back when I used it in the late 1990s) wasn't considered very high.

The trouble with undefined behavior is that no matter what result the compiler produces, that result is by definition correct (even if it is highly destructive and unpredictable).

Fortunately, very few compilers make an effort to actually cause unexpected behavior for such cases and the typical malloc implementation on machines used for HPC has some bookkeeping data just before the address it returns, so the decrement would typically give you a pointer into that bookkeeping data. It is not a good idea to write there, but just creating the pointer is harmless on those systems.

Just be aware that the code could break when the runtime environment gets changed or when the code is ported to a different environment.

Title: Pointer indexing

Body:
You are right that code such as

float a = malloc(size);
a--;

yields undefined behavior, per the ANSI C standard, section 3.3.6:

Unless both the pointer operand and the result point to a member of the same
  array object, or one past the last member of the array object, the behavior is undefined

For code like this, the quality of the C code in the book (back when I used it in the late 1990s) wasn't considered very high.

The trouble with undefined behavior is that no matter what result the compiler produces, that result is by definition correct (even if it is highly destructive and unpredictable).

Fortunately, very few compilers make an effort to actually cause unexpected behavior for such cases and the typical malloc implementation on machines used for HPC has some bookkeeping data just before the address it returns, so the decrement would typically give you a pointer into that bookkeeping data. It is not a good idea to write there, but just creating the pointer is harmless on those systems.

Just be aware that the code could break when the runtime environment gets changed or when the code is ported to a different environment.


问:
Do you have any techniques to help you get started in the morning?
I'm not a morning person.  I got into the habit of working from 10 to 7/8, sometimes 9.

Nevertheless, many of the places I've worked for have asked for something more like 8 to 6 or 9 to 6.

Honestly, I have a real tough time getting my brain going in the morning and getting into the code.  Once I do, I can concentrate for a long time and be quite productive.

It's getting into the code and starting to get going with it that I have trouble with.  Sometimes I will waste time in the morning just because I can't focus on the problem (yes, I am writing this in the morning).

I've put all my busy work in the morning, but as a developer, I don't have a lot of busy work.

It kind of becomes a self reinforcing thing; because you don't get things done in the morning, you have to stay later.  Because you have to stay later, then its harder to get started the next morning, etc.

Do other people have trouble with this?  If so, any techniques you've learned?

Thanks!

答:
Coffee.

No, seriously; I know it is bitter, but some of the espresso mixed drinks are actually really good.

Coffee in the morning helped me adjust from the late-night/sleeping in patterns of college to the 9-5 schedule of the real world.


答:
Officially, it's undefined behavior to have a pointer point outside the array (except for one past the end), even if it's never dereferenced.

In practice, if your processor has a flat memory model (as opposed to weird ones like x86-16), and if the compiler doesn't give you a runtime error or incorrect optimization if you create an invalid pointer, then the code will work just fine.

Title: Pointer indexing

Body:
I am currently reading a book titled "Numerical Recipes in C". In this book, the author details how certain algorithms inherently work better if we had indices starting with 1 (I don't entirely follow his argument and that isn't the point of this post), but C always indexes its arrays starting with 0. In order to get around this, he suggests simply decrementing the pointer after allocation, e.g.:

```<code>float *a = malloc(size);
a--;
</code>```

This, he says, will effectively give you a pointer that has an index starting with 1, which will then be free'd with:

```<code>free(a + 1);
</code>```

As far as I'm aware, though, this is undefined behavior by the C standard. This is apparently a highly reputable book within the HPC community, so I don't want to simply disregard what he's saying, but simply decrementing a pointer outside of the allocated range seems highly sketchy to me. Is this "allowed" behavior in C? I have tested it out using both gcc and icc, and both of those results appear to indicate that I'm worrying over nothing, but I want to be absolutely positive.


答:
...simply decrementing a pointer outside of the allocated range seems highly sketchy to me. Is this "allowed" behavior in C?

Allowed?  Yes.  Good idea?  Not Usually.

C is a shorthand for assembly language, and in assembly language there are no pointers, just memory addresses.  C's pointers are memory addresses that have a side behavior of incrementing or decrementing by the size of what they point to when subjected to arithmetic.  This makes the following just fine from a syntax perspective:

```<code>double *p = (double *)0xdeadbeef;
--p;  // p == 0xdeadbee7, assuming sizeof(double) == 8.
double d = p[0];
</code>```

Arrays aren't really a thing in C; they're just pointers to contiguous ranges of memory that behave like arrays.  The [] operator is a shorthand for doing pointer arithmetic and dereferencing, so a[x] actually means *(a + x).

There are valid reasons to do the above, such as some I/O device having a couple of doubles mapped into 0xdeadbee7 and 0xdeadbeef.  Very few programs would need to do that.

When you create the address of something, such as by using the & operator or calling malloc(), you want to keep the original pointer intact so you know that what it points to is actually something valid.  Decrementing the pointer means that some bit of errant code could try to dereference it, getting erroneous results, clobbering something or, depending on your environment, committing a segmentation violation.  This is especially true with malloc(), because you've put the burden on whoever's calling free() to remember to pass the original value and not some altered version that will cause all heck to break loose.

If you need 1-based arrays in C, you can do it safely at the expense of allocating one additional element that will never be used:

```<code>double *array_create(size_t size) {
    // Wasting one element, so don't allow it to be full-sized
    assert(size < SIZE_MAX);
    return malloc((size+1) * sizeof(double));
}

inline double array_index(double *array, size_t index) {
    assert(array != NULL);
    assert(index >= 1);  // This is a 1-based array
    return array[index];
}
</code>```

Note that this doesn't do anything to protect against exceeding the upper bound, but that's easy enough to handle.

Addendum:

Some chapter and verse from the C99 draft (sorry, that's all I can link to):

§6.5.2.1.1 says that the second ("other") expression used with the subscript operator is of integer type.  -1 is an integer, and that makes p[-1] valid and therefore also makes the pointer &(p[-1]) valid.  This does not imply that accessing memory at that location would produce defined behavior, but the pointer is still a valid pointer.

§6.5.2.2 says that the array subscript operator evaluates to the equivalent of adding the element number to the pointer, therefore p[-1] is equivalent to *(p + (-1)).  Still valid, but may not produce desirable behavior.

§6.5.6.8 says (emphasis mine):

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.

...if the expression P points to the i-th element of an
  array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N
  (where N has the value n) point to, respectively, the i+n-th and
  i−n-th elements of the array object, provided they exist.

This means that the results of pointer arithmetic have to point at an element in an array.  It does not say that the arithmetic has to be done all at once.  Therefore:

```<code>double a[20];

// This points to element 9 of a; behavior is defined.
double d = a[-1 + 10];

double *p = a - 1;  // This is just a pointer.  No dereferencing.

double e = p[0];   // Does not point at any element of a; behavior is undefined.
double f = p[1];   // Points at element 0 of a; behavior is defined.
</code>```

Do I recommend doing things this way?  I don't, and my answer explains why.

Title: Pointer indexing

Body:
...simply decrementing a pointer outside of the allocated range seems highly sketchy to me. Is this "allowed" behavior in C?

Allowed?  Yes.  Good idea?  Not Usually.

C is a shorthand for assembly language, and in assembly language there are no pointers, just memory addresses.  C's pointers are memory addresses that have a side behavior of incrementing or decrementing by the size of what they point to when subjected to arithmetic.  This makes the following just fine from a syntax perspective:

double *p = (double *)0xdeadbeef;
--p;  // p == 0xdeadbee7, assuming sizeof(double) == 8.
double d = p[0];

Arrays aren't really a thing in C; they're just pointers to contiguous ranges of memory that behave like arrays.  The [] operator is a shorthand for doing pointer arithmetic and dereferencing, so a[x] actually means *(a + x).

There are valid reasons to do the above, such as some I/O device having a couple of doubles mapped into 0xdeadbee7 and 0xdeadbeef.  Very few programs would need to do that.

When you create the address of something, such as by using the & operator or calling malloc(), you want to keep the original pointer intact so you know that what it points to is actually something valid.  Decrementing the pointer means that some bit of errant code could try to dereference it, getting erroneous results, clobbering something or, depending on your environment, committing a segmentation violation.  This is especially true with malloc(), because you've put the burden on whoever's calling free() to remember to pass the original value and not some altered version that will cause all heck to break loose.

If you need 1-based arrays in C, you can do it safely at the expense of allocating one additional element that will never be used:

double *array_create(size_t size) {
    // Wasting one element, so don't allow it to be full-sized
    assert(size < SIZE_MAX);
    return malloc((size+1) * sizeof(double));
}

inline double array_index(double *array, size_t index) {
    assert(array != NULL);
    assert(index >= 1);  // This is a 1-based array
    return array[index];
}

Note that this doesn't do anything to protect against exceeding the upper bound, but that's easy enough to handle.

Addendum:

Some chapter and verse from the C99 draft (sorry, that's all I can link to):

§6.5.2.1.1 says that the second ("other") expression used with the subscript operator is of integer type.  -1 is an integer, and that makes p[-1] valid and therefore also makes the pointer &(p[-1]) valid.  This does not imply that accessing memory at that location would produce defined behavior, but the pointer is still a valid pointer.

§6.5.2.2 says that the array subscript operator evaluates to the equivalent of adding the element number to the pointer, therefore p[-1] is equivalent to *(p + (-1)).  Still valid, but may not produce desirable behavior.

§6.5.6.8 says (emphasis mine):

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.

...if the expression P points to the i-th element of an
  array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N
  (where N has the value n) point to, respectively, the i+n-th and
  i−n-th elements of the array object, provided they exist.

This means that the results of pointer arithmetic have to point at an element in an array.  It does not say that the arithmetic has to be done all at once.  Therefore:

double a[20];

// This points to element 9 of a; behavior is defined.
double d = a[-1 + 10];

double *p = a - 1;  // This is just a pointer.  No dereferencing.

double e = p[0];   // Does not point at any element of a; behavior is undefined.
double f = p[1];   // Points at element 0 of a; behavior is defined.

Do I recommend doing things this way?  I don't, and my answer explains why.


问:
A vector of pointers to different derived classes of the same base class
I am writing a game in C++ which has different enemy types. I have defined a base Enemy class and I also have derived classes enemy1, enemy2 etc.
Now for updating these enemies in each iteration of the game, I want to have an array: EnemyArray with its elements pointing to the existing enemies so that I can make sure to update them all with their own version of update(), etc.

One way of doing this, would be to define separate arrays for each enemy type and that would be a clean way of solving the problem. However, I was wondering if the fact that these enemy classes are all derived from the same base class makes it possible to somehow have my EnemyArray as an array of Enemy's and do some modifications later.

答:
(I'm assuming C++)

std::vector holds its elements by value so if you store subclasses you are slicing the objects.

You can use the PImpl idiom to avoid this, you have a concrete Enemy class that holds a (unique) pointer to a concrete enemy an abstract IEnemy that holds the custom code.

```<code>class Enemy
{
  Point location;
  std::unique_ptr<IEnemy> pimpl;

  public:
    Enemy(IEnemy&& pimpl): pimpl(pimpl), location(){}

    void onTick(World w){
        pimpl->onTick(w);
    }
}
</code>```

You can instead hold pointers in you vector std::vector<std::unique_ptr<Enemy>> so it doesn't hold them by value.

Body:
(I'm assuming C++)

std::vector holds its elements by value so if you store subclasses you are slicing the objects.

You can use the PImpl idiom to avoid this, you have a concrete Enemy class that holds a (unique) pointer to a concrete enemy an abstract IEnemy that holds the custom code.

class Enemy
{
  Point location;
  std::unique_ptr<IEnemy> pimpl;

  public:
    Enemy(IEnemy&& pimpl): pimpl(pimpl), location(){}

    void onTick(World w){
        pimpl->onTick(w);
    }
}

You can instead hold pointers in you vector std::vector<std::unique_ptr<Enemy>> so it doesn't hold them by value.


答:
You can specify base class with virtual function Update and derived classes overriding this function. Here is simple example:

```<code>class Enemy
{
public:
    // this is abstract function, but you can also add implementation
    // as default behavior for derived classes
    virtual void Update() = 0;
};

class Enemy1 : public Enemy
{
public:
    void Update()
    {
        // update Enemy
    }
}

class Enemy2 : public Enemy
{
    void Update()
    {
        // update Enemy
    }
}
</code>```

Then create a vector of pointers to base class and fill with objects of specific type:

```<code>vector<Enemy*> enemies;
enemies.push_back(new Enemy1());
enemies.push_back(new Enemy2());
</code>```

And your UpdateAll function can look like this:

```<code>void UpdateAll()
{
    for (int i = 0; i < enemies.size(); ++i)
    {
        enemies[i]->Update();
    }
}
</code>```

Because you are using pointers, don't forget to release all allocated memory at the end of game.

Title: A vector of pointers to different derived classes of the same base class

Body:
I am writing a game in C++ which has different enemy types. I have defined a base Enemy class and I also have derived classes enemy1, enemy2 etc.
Now for updating these enemies in each iteration of the game, I want to have an array: EnemyArray with its elements pointing to the existing enemies so that I can make sure to update them all with their own version of update(), etc.

One way of doing this, would be to define separate arrays for each enemy type and that would be a clean way of solving the problem. However, I was wondering if the fact that these enemy classes are all derived from the same base class makes it possible to somehow have my EnemyArray as an array of Enemy's and do some modifications later.

Body:
You can specify base class with virtual function Update and derived classes overriding this function. Here is simple example:

class Enemy
{
public:
    // this is abstract function, but you can also add implementation
    // as default behavior for derived classes
    virtual void Update() = 0;
};

class Enemy1 : public Enemy
{
public:
    void Update()
    {
        // update Enemy
    }
}

class Enemy2 : public Enemy
{
    void Update()
    {
        // update Enemy
    }
}

Then create a vector of pointers to base class and fill with objects of specific type:

vector<Enemy*> enemies;
enemies.push_back(new Enemy1());
enemies.push_back(new Enemy2());

And your UpdateAll function can look like this:

void UpdateAll()
{
    for (int i = 0; i < enemies.size(); ++i)
    {
        enemies[i]->Update();
    }
}

Because you are using pointers, don't forget to release all allocated memory at the end of game.