答:
They can be: As noted in other answers getters/setters by definition provide some encapsulation of the field within the object. There are some pitfalls however. The pseudo code below for instance allows client code to mess about with the internals of the objects of type Foo, because the list 'bars' is a mutable object, so client can do anything to - like clearing it or adding new stuff to. This in my view is a clear violation of encapsulation.

```<code>class Foo
{
    private List bars = new List();

    public List GetBars()
    {
        return bars;
    }
}
</code>```

To alleviate this either don't provide the getter for bars at all or have it return a readonly copy of the list:

```<code>class Foo
{
    private List bars = new List();

    public List GetBars()
    {
        return bars.AsReadOnly();
    }
}
</code>```

This problem is not specific to lists, but can turn up with any mutable complex type returned from a getter.

Body:
They can be: As noted in other answers getters/setters by definition provide some encapsulation of the field within the object. There are some pitfalls however. The pseudo code below for instance allows client code to mess about with the internals of the objects of type Foo, because the list 'bars' is a mutable object, so client can do anything to - like clearing it or adding new stuff to. This in my view is a clear violation of encapsulation.

class Foo
{
    private List bars = new List();

    public List GetBars()
    {
        return bars;
    }
}

To alleviate this either don't provide the getter for bars at all or have it return a readonly copy of the list:

class Foo
{
    private List bars = new List();

    public List GetBars()
    {
        return bars.AsReadOnly();
    }
}

This problem is not specific to lists, but can turn up with any mutable complex type returned from a getter.


问:
Is there a way to prevent others to steal your open source project and use it to make a profit?
This might seems like a silly question to ask, but I can't really figure out the answer. The title pretty much says it all.

Let's say you have an open source music player, along comes someone, copies it, adds features, modifies the interface, etc and sells it. Nobody would find out. So how does it work?

Related: I'm working in some projects myself to make me more employable, so employers can take a look at my code but with some of them I don't feel like uploading them to an online repository, ie sourceforge, and make them visible for the general public.

答:
Let's say you have an open source music player, along comes someone, copies it, adds features, modifies the interface, etc and sells it. Nobody would find out. So how does it work?

Pretty much like you described, except someone has to find out. If he doesn't, then no, you don't know. Which is pretty much the way it goes in a lot of software nowadays. Code and ideas get stolen, ... deal with it, always did, always will.

If somehow you do find out someone "ripped you off", then, presuming your country's laws apply and you have means to pursue, you can take them to court. Which depending on the juridisticial system you're under, can mean you have a practical shot at winning that or only a theoretical one at best.

Related: I'm working in some projects myself to make me more employable, so employers can take a look at my code but with some of them I don't feel like uploading them to an online repository, ie sourceforge, and make them visible for the general public.

Well, either make it a private/public repo. i.e. with a designated login/pass for visitors, a repo which mirrors your main repo where you keep most of your stuff (you don't want to be giving your main acc. to someone) or just mail to them or something. Or put it on a web page not easily found in the vasts of the web. Dropbox link also works.

Also, don't give all of your code (the complete package) away, remove the few relevant bits, but supply the binary. They can see the code and the app, but they can't build the app that way for themselves.

ContentLicense: CC BY-SA 3.0


问:
Doubt regarding search engine/plugin(One present on the website itself)
I am new to web development and trying to study various types of websites as case study. Right now my focus is on how search engines works for an eCommerce website.

I know basic functioning for a search engine, i.e. crawl web pages, index them and the display the results using those indexes.

But I got little confuse in case of an eCommerce website. Don't you think that it would be better if a search engine instead of crawling the web pages containing products, it should directly crawl the database and index the products stored in the database? And when a user search for any product, it will simply give us the rows of the table which matches the user query?

If this is not the case, can someone please explain how the usual method works on eCommerce website?

答:
Generally, a website like an e-commerce website, and usually also news websites, blogs and anything else with highly structured pages (such as Stack Overflow itself -- though don't try looking for it), will publish an XML sitemap file.

An XML sitemap is basically just a big XML file with a bunch of links to all of the pages in the site. It usually also includes the relative "importance" of each page within the site (so a product page is more important than a category listing, for example) which helps the search engine to decide what to prefer to display in a result page.

Because the sitemap.xml file may be really big (several megabytes for a large site), Google and other search engines also accept more specialized sitemap files. For example, a "News Sitemap" will contains links to all news stories published by a news website in the last 48 hours. Google will "ping" that file much more frequently (even up to once every couple of minutes) to check whether new stories have been published -- this is how they keep http://google.com/news up-to-date.

Note that the sitemap file only contains links to pages within the site. It's not a dump of the database or anything like that. This is because search engines are specifically interested in indexing a site the same way that human would read it. That's why they put so much emphasis on penalizing you from "tricking" it into indexing something a human would never actually see (hidden text and whatnot).

Edit

In response to your question, for the "internal" search functionality, yes most of these will be implemented using a direct search of the database, rather than the typical "public" search engine technique of crawl/index/query.

To make the searching faster, typically something like Lucene is used (some databases provide in-built full-text search functionality as well, but Lucene is more full-featured than any in-built full-text search I've seen). Basically, what comes out of a Lucene search will be the identifier of the products/blog post/news item your query matched, and then you'll fetch those results from the database to display however you like.

However, that can be fairly complex to set up. Many sites will just use something like a Google Custom Search, which basically just does a regular Google search with "site:example.com" pre-pended to the query string. It usually returns worse results than Lucene, but it's pretty trivial to set up.


问:
Are Get-Set methods a violation of Encapsulation?

Possible Duplicate:

  When are Getters and Setters Justified

In an Object oriented framework, one believes there must be strict encapsulation. Hence, internal variables are not to be exposed to outside applications.

But in many codebases, we see tons of get/set methods which essentially open a formal window to modify internal variables that were originally intended to be strictly prohibited. Isn't it a clear violation of encapsulation? How broadly such a practice is seen and what to do about it?

EDIT:

I have seen some discussions where there are two opinions in extreme: on one hand people believe that because get/set interface is used to modify any parameter, it does qualifies not be violating encapsulation. On the other hand, there are people who believe it is does violate.

Here is my point. Take a case of UDP server, with methods - get_URL(), set_URL(). The URL (to listen to) property is quite a parameter that application needs to be supplied and modified. However, in the same case, if the property like get_byte_buffer_length() and set_byte_buffer_length(), clearly points to values which are quite internal. Won't it imply that it does violate the encapsulation? In fact, even get_byte_buffer_length() which otherwise doesn't modify the object, still misses the point of encapsulation, because, certainly there is an App which knows i have an internal buffer! Tomorrow, if the internal buffer is replaced by something like a packet_list the method goes dysfunctional.

Is there a universal yes/no towards get set method? Is there any strong guideline that tell programmers (specially the junior ones) as to when does it violate encapsulation and when does it not?

答:
They can be! The example you provide seems to be a good example where they are.
Such methods provide access on a very low level of abstraction, and don't encapsulate the user of the class from the details. That does not mean that a class like this is wrong or bad, it depends on the intended usage. </p>

<p>The Server in your example would IMO be much better take a buffer policy (at construction with a reasonable default, like dynamic buffer) so that it can answer read or send requests without the user caring or even knowing about the details of the buffer management if sHe doesn't want to. </p>

Body:
They can be! The example you provide seems to be a good example where they are.
Such methods provide access on a very low level of abstraction, and don't encapsulate the user of the class from the details. That does not mean that a class like this is wrong or bad, it depends on the intended usage.

The Server in your example would IMO be much better take a buffer policy (at construction with a reasonable default, like dynamic buffer) so that it can answer read or send requests without the user caring or even knowing about the details of the buffer management if sHe doesn't want to.


答:
As far as I can  make out, the most common way to find out is by some whistle blower in the company who does the ripping off.

If you are really worried about this, you may consider posting a reward of some kind for whistle blowers.

You may also find this site useful in the event of code being ripped off.

http://www.softwarefreedom.org/

Title: Is there a way to prevent others to steal your open source project and use it to make a profit?

Body:
This might seems like a silly question to ask, but I can't really figure out the answer. The title pretty much says it all.

Let's say you have an open source music player, along comes someone, copies it, adds features, modifies the interface, etc and sells it. Nobody would find out. So how does it work?

Related: I'm working in some projects myself to make me more employable, so employers can take a look at my code but with some of them I don't feel like uploading them to an online repository, ie sourceforge, and make them visible for the general public.


问:
How to document/verify consistent layering?
I have recently moved to the dark side: I am now a CUSTOMER of software development -- mainly websites. With this new role comes new concerns.

As a programmer i know how solid an application becomes when it is properly layered, and I want to use this knowledge in my new job. I don't want business logic in my presentation layer, and certainly not presentation stuff in my data layer. Thus, I want to be able to demand from my supllier that they document the level of layering, and how neat and consistent the layering is.

The big question is: How is the level of layering documented to me as a customer, and is that a reasonable demmand for me to have, so I don't have to look in the code (I'm not supposed to do that anymore)?

答:
This is reasonable - as a customer you can require anything you want, and using good layering as an indication of code quality and separation of concerns is a valid requirement.

There are many tools out there that will help with such documentation - some of them will produce an image of the Directed Acyclic Graph, showing you that the lower down layers are not calling the higher up levels. Some static analysis tools will do so too.

Getting a representation of the DAG is probably what will give you the most idea regarding how layering works in the code base.

In the .NET world, NDepend is a good commercial tool that will help with visualizing the high level architecture and layering of anapplication.


答:
I generally try to avoid public setters - if data needs to be provided to an object it ought to go in via method parameters or the constructor. By setting a property externally you are potentially undermining the integrity of that object.

Encapsulation is more about the semantics of the public API that the object exposes...

Take a simple class with a Name property:

```<code>public class Foo
{
    public String Name { get; set; }
}
</code>```

I would prefer to write this as (given this is a very simple example):

```<code>public class Foo
{
    public String Name { get; private set; }

    public void Rename(String name)
    {
        this.Name = name;
    }
}
</code>```

The goal here is that you're not directly modifying the state of the object from the outside... you're invoking some piece of behaviour, and it's that behaviour which has an observable effect on the objects internal state.

This pattern can be enhanced further with immutability:

```<code>public class Foo
{
    // Clone constructor...
    private Foo(foo prototype) { ... }

    public String Name { get; private set; }

    public Foo Rename(String name)
    {
        return new Foo(this)
        {
            Name = name
        };
    }
}
</code>```

Title: Are Get-Set methods a violation of Encapsulation?

Body:
Possible Duplicate:

  When are Getters and Setters Justified

In an Object oriented framework, one believes there must be strict encapsulation. Hence, internal variables are not to be exposed to outside applications.

But in many codebases, we see tons of get/set methods which essentially open a formal window to modify internal variables that were originally intended to be strictly prohibited. Isn't it a clear violation of encapsulation? How broadly such a practice is seen and what to do about it?

EDIT:

I have seen some discussions where there are two opinions in extreme: on one hand people believe that because get/set interface is used to modify any parameter, it does qualifies not be violating encapsulation. On the other hand, there are people who believe it is does violate.

Here is my point. Take a case of UDP server, with methods - get_URL(), set_URL(). The URL (to listen to) property is quite a parameter that application needs to be supplied and modified. However, in the same case, if the property like get_byte_buffer_length() and set_byte_buffer_length(), clearly points to values which are quite internal. Won't it imply that it does violate the encapsulation? In fact, even get_byte_buffer_length() which otherwise doesn't modify the object, still misses the point of encapsulation, because, certainly there is an App which knows i have an internal buffer! Tomorrow, if the internal buffer is replaced by something like a packet_list the method goes dysfunctional.

Is there a universal yes/no towards get set method? Is there any strong guideline that tell programmers (specially the junior ones) as to when does it violate encapsulation and when does it not?

Body:
I generally try to avoid public setters - if data needs to be provided to an object it ought to go in via method parameters or the constructor. By setting a property externally you are potentially undermining the integrity of that object.

Encapsulation is more about the semantics of the public API that the object exposes...

Take a simple class with a Name property:

public class Foo
{
    public String Name { get; set; }
}

I would prefer to write this as (given this is a very simple example):

public class Foo
{
    public String Name { get; private set; }

    public void Rename(String name)
    {
        this.Name = name;
    }
}

The goal here is that you're not directly modifying the state of the object from the outside... you're invoking some piece of behaviour, and it's that behaviour which has an observable effect on the objects internal state.

This pattern can be enhanced further with immutability:

public class Foo
{
    // Clone constructor...
    private Foo(foo prototype) { ... }

    public String Name { get; private set; }

    public Foo Rename(String name)
    {
        return new Foo(this)
        {
            Name = name
        };
    }
}


问:
Should we write detailed architecture design or just an outline when designing a program?
When I'm doing design for a task, I keep fighting this nagging feeling that aside from being a general outline it's going to be more or less ignored in the end. I'll give you an example:

I was writing a frontend for a device that has read/write operations. It made perfect sense in the class diagram to give it a read and a write function. Yet when it came down to actually writing them I realized they were literally the same function with just one line of code changed (read vs write function call), so to avoid code duplication I ended up implementing a do_io function with a parameter that distinguishes between operations. Goodbye original design.

This is not a terribly disruptive change, but it happens often and can happen in more critical parts of the program as well, so I can't help but wondering if there's a point to design more detail than a general outline, at least when it comes to the program's architecture (obviously when you are specifying an API you have to spell everything out).

This might be just the result of my inexperience in doing design, but on the other hand we have agile methodologies which sort of say "we give up on planning far ahead, everything is going to change in a few days anyway", which is often how I feel.

So, how exactly should I "use" design?

答:
The amount of time you spend on the architecture should be determined by the degree of risk in that part of the system.

Generally you'll want to make a decision fairly early on the architectural style(s) - layered, component, pub-sub, etc, etc. No amount of clean code and loose coupling is going to make it easy to switch styles late in a project.

Doing that will give you a basic idea of the different building blocks in your system and what the roadmap will be as your system and requirements evolve over time.

Once you get into use cases I believe you should do enough design to ensure you understand the problem and solution fully. If it's boiler plate code that you've done again and again then the risk of getting it wrong (in an architectural sense - you'll still need to test of course) is pretty low and so the amount of up-front design is likely to be fairly minimal. If it's a new problem, or one with an unclear solution or one that is potentially risky to the business then it'll deserve much more time thinking things through.

There are of course a wide range of ways of doing this - UML, prototypes, white board sketches, etc. Whichever method you use - the key thing is to remember is that their purpose is to help you think and communicate about your design.


答:
You have worked as a programmer, you probably have seen projects fail/take longer than expected and you know that you don't want that as a client.

You have every right to demand such a thing.

What I would suggest is apart from documenting the layers of the application have them run their unit/intergration tests in front of you.

How they organize their tests will tell you more about the code than just the documentation and you won't even have to see it.

Title: How to document/verify consistent layering?

Body:
I have recently moved to the dark side: I am now a CUSTOMER of software development -- mainly websites. With this new role comes new concerns.

As a programmer i know how solid an application becomes when it is properly layered, and I want to use this knowledge in my new job. I don't want business logic in my presentation layer, and certainly not presentation stuff in my data layer. Thus, I want to be able to demand from my supllier that they document the level of layering, and how neat and consistent the layering is.

The big question is: How is the level of layering documented to me as a customer, and is that a reasonable demmand for me to have, so I don't have to look in the code (I'm not supposed to do that anymore)?


问:
What are functional-programming ways of implementing Conway's Game of Life
I recently implemented for fun Conway's Game of Life in Javascript (actually coffeescript but same thing). Since javascript can be used as a functional language I was trying to stay to that end  of the spectrum. I was not happy with my results. I am a fairly good OO programmer and my solution smacked of same-old-same-old. So long question short: what is the (pseudocode) functional style of doing it?

Here is Pseudocode for my attempt:

```<code>class Node
  update: (board) ->
    get number_of_alive_neighbors from board
    get this_is_alive from board
    if this_is_alive and number_of_alive_neighbors < 2 then die
    if this_is_alive and number_of_alive_neighbors > 3 then die
    if not this_is_alive and number_of_alive_neighbors == 3 then alive

class NodeLocations
  at: (x, y) -> return node value at x,y
  of: (node) -> return x,y of node

class Board
  getNeighbors: (node) ->
   use node_locations to check 8 neighbors
   around node and return count

nodes = for 1..100 new Node
state = new NodeState(nodes)
locations = new NodeLocations(nodes)
board = new Board(locations, state)

executeRound:
  state = clone state
  accumulated_changes = for n in nodes n.update(board)
  apply accumulated_changes to state
  board = new Board(locations, state)
</code>```

答:
Well, a couple of ideas. I'm not an expert in FP, but...

It's fairly clear we should have a type Board which represents a game state. The basis of the implementation should be an evolve function of type evolve :: Board -> Board; meaning it produces a Board from applying the rules of the game to a Board.

How should we implement evolve? A Board should probably be an n x m matrix of Cells. We could implement a function cellEvolve of type cellEvolve :: Cell -> [Cell] -> Cell which given a Cell and its neighboring Cells calculates the Cell state in the next iteration.

We should also implement a getCellNeighbors function which extracts a Cells neighbors from a Board. I'm not entirely sure of the signature of this method; depending on how you implement Cell and Board you could have for instance getCellNeighbors :: Board -> CoordElem -> CoordElem -> [Cell], which given a Board and two coordinates (CoordElem would be the type used to index positions in a Board), gives you a variable length list of the neighbors (not all cells in the board have the same number of neighbors- corners have 3 neighbors, borders 5 and everyone else, 8).

evolve can thus be implemented by combining cellEvolve and getCellNeighbors for all cells in the board, again the exact implementation will depend on how you implement Board and Cell, but it should be something like "for all cells in the current board, get their neighbors and use them to calculate the new board's corresponding cell'. This should be possible to do with a generic application of those functions over the whole board using a "map over board's cell function".

Other thoughts:

You should really implement cellEvolve so that it takes as a parameter a type GameRules which encodes the rules of the game- say a list of tuples (State,[(State,NumberOfNeighbors)],State) which says for a given state and the number of neighbors in each state, which should be the state in the next iteration. cellEvolve's signature could then be cellEvolve :: GameRules -> Cell -> [Cell] -> Cell

This would logically take you to making evolve :: Board -> Board turn into evolve :: GameRules -> Board -> Board, so that you could use evolve unchanged with different GameRules, but you could go a step further and make cellEvolve pluggable instead of GameRules.

Playing with getCellNeighbors you could also make evolve generic with regards to the Board's topology- you could have getCellNeighbors which wrap around either board's edges, 3d boards, etc.


问:
Is JSF really ready to deliver high performance web applications?
I have heard a lot of good about JSF but as far as I know people also had lots of serious complains with this technology in the past, not aware of how much the situation has improved. We are considering JSF as a probable technology for a social network project. But we are not aware of the performance scores of JSF neither we could really come across any existing high performance website that had been using JSF. People complain about its performance scalability issues.

We are still not very sure if we are doing the right thing by choosing jsf, and thus would like to hear from you all about this and take your inputs into consideration.

Is it possible to configure JSF to satisfy the high performance needs of social networking service ? Also till what extent is it possible to survive with the current problems in JSF. What exactly are its problems ?

I am not  worried about the development complexities with JSF what others usually complain about because as per my personal experience I believe that's not at all true, but I am more concerned about what performance and scalability issues. And please don't just abuse it on its old issues linked to previous versions. I just care about the present state whatever had been its past.

答:
An article that might help a little (although not really conclusive) is Server Centric Java Frameworks: Performance Comparison at DZone Javalobby:

...This article reviews how much effective most of the SPI Java web frameworks are on partial changes provided by the server. We are not interested in events with no server communication, that is, events with no (possible) server control.

How they are going to be measured

We are going to measure the amount of code that is sent to client regarding to the visual change performed in client.

For instance for a minor visual change (some new data) in a component we expect not much code from server, that is, the new markup needed as plain HTML, or embedded in JavaScript, or some high level instructions containing the new data to be visualized. Otherwise something seems wrong for instance the complete component or page zone is rebuilt, wasting bandwidth and client power (and maybe server power).

Because we will use public demos, we are not going to get a definitive and fine grain benchmark. But you will see very strong differences between frameworks.

The testing technique is very easy and everybody can do it with no special infrastructure, we just need FireFox and FireBug. In this test FireFox 3.6.8 and FireBug 1.5.4 are used.

The FireBug Console when "Show XMLHttpRequests" is enabled logs any AJAX request showing the server response...

Frameworks tested

RichFaces, IceFaces,  MyFaces/Trinidad, OpenFaces, PrimeFaces, Vaadin, ZK, ItsNat

...apparently the only JSF implementation free of serious performance penalties is PrimeFaces...

I haven't been able to find a proper comparison (for performance), if anyone finds one I'd love to see it!


问:
How can I refactor client side functionality to create a product line-like generic design?
Assume the following situation similar to that of Stack Overflow: I have a system with a front-end that can perform various manipulations on the data (by sending messages to REST back-end):

Posting

Editing and deleting

Adding labels and tags

Now in the first version we created it well modularized but the need as of now for 'evolving' the system similar to Stack Overflow. My question is how best to separate the commonality and how to incorporate the variability with respect to the following:

Commonality:

The above 'functionalities' and sending/receiving the data from the server

Look and feel (also a variability as explained below)

HTTP verbs associated with the above actions

Variability:

The RESTful URLs where the requests are sent

The text/style of the UI (the commonality is analogous to Stack Overflow - the functionality of upvotes, posting a question remains the same, but the words, the icons, the look and feel is still different across sites)

I think this is entirely a client-side code organization/refactoring issue. I'm heavily using jQuery, javascript and backbone for front-end development.

My question is how best should I isolate the same to be able to create multiple such aspects to the tool we are currently working on?

答:
The RESTful URLs where the requests are sent

Is this just a simple case of the URLs being something like:

http://mysite1.com/api/post

http://random.site.com/api/post

etc.

(meaning, the API's base is variable, but the paths within are not)? If that's it, basically your REST-caller should do ${apibase}/api/post and plug in different values for apibase in the right place (application instance configuration).

The text/style of the UI

Being able to define different CSSs and text. CSS should be easy, for short texts you could probably retrofit your platform's i18n features and for long texts you could probably do with parameterizable includes, something akin to:

```<code>include("path/to/mylongtextresource-${sitename}.html")
</code>```

Addressing your comment:

My ENTIRE URI is different - things ARE different in a restful world since it's very resource oriented. In your example the same 'type' of resources exist for the base resource. Yes, I do have them too and that's exactly how they are handled. But I feel the answer misses the point of the question. I need to 'structure' my code so that 'another' restful resource with 'similar structure' (e.g.,: /Site/{resource}/{id}/{sub-resource}/{id}/) can easily be added to the system with minimal changes

I'd use something like the following (pseudo-java):

```<code>interface ResourceService {
    public String getContent(String id, String subResource, String subId);
}

Map<String,ResourceService> services = {"resourceA" : new AResourceService(), "resourceB", new BResourceService(), ...};

@URLMap("/Site/{resource}/{id}/{sub-resource}/{id}/")
String getContent(String resource, String id, String subResource, String subId) {
    return services.get(resource).getContent(id, subResource, subId);
}
</code>```

Meaning you can add programatically new ResourceServices to your Controller. You could also do it two-level if needed.

OwnerDisplayName: Nupul

Body:
The RESTful URLs where the requests are sent

Is this just a simple case of the URLs being something like:

http://mysite1.com/api/post

http://random.site.com/api/post

etc.

(meaning, the API's base is variable, but the paths within are not)? If that's it, basically your REST-caller should do ${apibase}/api/post and plug in different values for apibase in the right place (application instance configuration).

The text/style of the UI

Being able to define different CSSs and text. CSS should be easy, for short texts you could probably retrofit your platform's i18n features and for long texts you could probably do with parameterizable includes, something akin to:

include("path/to/mylongtextresource-${sitename}.html")

Addressing your comment:

My ENTIRE URI is different - things ARE different in a restful world since it's very resource oriented. In your example the same 'type' of resources exist for the base resource. Yes, I do have them too and that's exactly how they are handled. But I feel the answer misses the point of the question. I need to 'structure' my code so that 'another' restful resource with 'similar structure' (e.g.,: /Site/{resource}/{id}/{sub-resource}/{id}/) can easily be added to the system with minimal changes

I'd use something like the following (pseudo-java):

interface ResourceService {
    public String getContent(String id, String subResource, String subId);
}

Map<String,ResourceService> services = {"resourceA" : new AResourceService(), "resourceB", new BResourceService(), ...};

@URLMap("/Site/{resource}/{id}/{sub-resource}/{id}/")
String getContent(String resource, String id, String subResource, String subId) {
    return services.get(resource).getContent(id, subResource, subId);
}

Meaning you can add programatically new ResourceServices to your Controller. You could also do it two-level if needed.


问:
How to drastically improve code coverage?
I'm tasked with getting a legacy application under unit test. First some background about the application: It's a 600k LOC Java RCP code base with these major problems

massive code duplication

no encapsulation, most private data is accessible from outside, some of the business data also made singletons so it's not just changeable from outside but also from everywhere.

no abstractions (e.g. no business model, business data is stored in Object[] and double[][]), so no OO.

There is a good regression test suite and an efficient QA team is testing and finding bugs. I know the techniques how to get it under test from classic books, e.g. Michael Feathers, but that's too slow. As there is a working regression test system I'm not afraid to aggressively refactor the system to allow unit tests to be written.

How should I start to attack the problem to get some coverage quickly, so I'm able to show progress to management (and in fact to start earning from safety net of JUnit tests)? I do not want to employ tools to generate regression test suites, e.g. AgitarOne, because these tests do not test if something is correct.

答:
I believe there are two main axes along which code can be placed when it comes to introducing unit tests: A) how testable is the code? and B) how stable is it (i.e. how urgently does it need tests)? Looking only at the extremes, this yields 4 categories:

Code that is easy to test and brittle

Code that is easy to test and stable

Code that is hard to test and brittle

Code that is hard to test and stable

Category 1 is the obvious place to start, where you can get much benefit with relatively little work. Category 2 allows you to quickly improve your coverage statistic (good for morale) and get more experience with the codebase, while category 3 is more (often frustrating) work but also yields more benefit. Which you should do first depends on how important morale and coverage statistics are for you. Category 4 is probably not worth bothering with.


问:
Is there a correlation between complexity and reachability?
I've been studying cyclomatic complexity (McCabe) and reachability of software at uni recently. Today my lecturer said that there's no correlation between the two metrics, but is this really the case?

I'd think there would definitely be some correlation, as less complex programs (from the scant few we've looked at) seem to have 'better' results in terms of reachability.

Does anyone know of any attempt to look at the two metrics together, and if not, what would be a good place to find data on both complexity and reachability for a large(ish) number of programs?

答: I'm not familiar with reachability, but if it's a measure of code paths which cannot ever be executed, cyclomatic complexity should be sort of an upper bound of that.</p>


问:
Do you need to know Java before trying Scala
I'm interested in learning Scala. I've been reading a lot about it, but a lot of people value it because it has an actor model which is better for concurrency, it handles xml in a much better way, solves the problem of first class functions.

My question is do you need to know Java to understand/appreciate the way things work in Scala?
Is it better to first take a stab at Java and then try Scala or you can start Scala with absolutely no java backround?

答:
Scala is its own language, and by itself doesn't require knowledge of any existing languages. If you wanted to, you could learn Scala as your first language. On the Learning Scala page of their website, there are entry points to the tutorial for different levels of experience, ranging from first-time programmers to programming language researchers to functional programming experts.

Most of the documentation is focused on people who know how to program, unfortunately, but I've actually worked through some of the Scala tutorials. It's not that bad. It's expected that you understand certain basic concepts, though.


问:
How should a developer reject impossible requirements?
Here's the problem I'm facing:

Quote From Project Manager:

Hey Spark, I'm assigning you the task of developing a framework that could be used for many different iOS applications. Here are the requirements:

It should be able to detect the thickness of the thumb or fingers being used to manipulate the UI.

With this information, all elements of the UI should be arranged & sized automatically.

For a larger thumb, elements should be arranged nearer the center of the screen.

For a smaller thumb, elements should be arranged nearer the corners of the screen.

For a larger thumb, all fonts should be smaller. (We're assuming an adult in this case.)

For a smaller thumb, all fonts should be larger. (We're assuming a younger person in this case.)

Summary:

This framework is required for creating user-friendly user interfaces programmatically. The framework should be developed in such a way that we can use for as many projects as needed, so it must also be very developer-friendly.

I am the developer given this task, so my questions are as follows:

How can I explain that these requirements are a little ridiculous?

How can I explain that it would be better to concentrate on developing actual projects?

How can I explain that even if this were possible, I wouldn't recommended developing such a thing?

How do I say NO to this project politely, gently, and respectfully?

How can I explain that even for a developer with 3 years of experience, this might not be possible?

答:
If you get a set of requirements that are physically impossible to implement as the device does not support and cannot support the wanted functionality, you need to explain this to the person creating the requirements.

You should be respectful and explain why the requirements are not possible to implement (i.e. the touch screen cannot distinguish between a thumb, finger or stylus. It does not have enough resolution in order to detect finger width.) - keep things factual, pointing to existing documentation if there is any.

Do not go into any sort of emotional argument and keep cool and professional. Saying to anyone that their requirements are silly is never a winning strategy.

See if you can get an understanding of the actual goals for the feature - why it is seen as a requirement. This could lead you to a different, better feature that will solve the need. (thanks @spoike)

@DarkStar33 suggests in the comments to do the research and provide an actual estimate of how much the project will cost and how long it will take, with the assumption that the result will be too expensive and lengthy to be worth it. Being armed with numbers and the data to back them up can certainly help your case, though I would still look at the business goals to see if they can be met (even partially) in another fashion.


问:
Which database should I use to manage relationship?
I need 2 capabilities:

calculating mutual friends distinguishing between different types of edges, (e.g. FRIEND, ENEMY and other)

getting relationships distinguishing between different types of edges as over

My problem is speed: If I use a database as MySQL, I can get thousands of relationships in few moments, but if I need to calculate mutual friends, it costs a lot for my server, doesn't it?

I've about 100,000 accounts on my site, and I want to introduce a relationship system, but obviously I have to decide the right way to develop it. Do you have any idea?

答:
Since you have 100k user accounts on site, I will run a quick estimate for you:

100k accounts

[assumption] ~30% of accounts are actually active

[assumption] ~20% of active accounts will have 100 relationships on average

[assumption] ~80% of active accounts will have 10 relationship on average

Or in other words:

70k users are basically inactive

24k users will have 10 relationships on average

6k users will have 100 relationships on average

This means that your many-to-many relationship table will have:

70k * 0 + 24k * 10 + 6k * 100 = 840k rows or ~1 million rows

Honestly, 1M rows is peanuts for a properly configured RDBMS. Furthermore, you will probably able to cope until you have around a few million accounts by just scaling up.

Note: the assumption is that you add a table similar to this:

```<code>SourceUserId, DestinationUserId, LoveOrHate
</code>```

Body:
Since you have 100k user accounts on site, I will run a quick estimate for you:

100k accounts

[assumption] ~30% of accounts are actually active

[assumption] ~20% of active accounts will have 100 relationships on average

[assumption] ~80% of active accounts will have 10 relationship on average

Or in other words:

70k users are basically inactive

24k users will have 10 relationships on average

6k users will have 100 relationships on average

This means that your many-to-many relationship table will have:

70k * 0 + 24k * 10 + 6k * 100 = 840k rows or ~1 million rows

Honestly, 1M rows is peanuts for a properly configured RDBMS. Furthermore, you will probably able to cope until you have around a few million accounts by just scaling up.

Note: the assumption is that you add a table similar to this:

SourceUserId, DestinationUserId, LoveOrHate


答:
People at Apple already deeply thought of all these things and they didn't come up with a resizable interface depending on thumb/fingers sizes.

As a user, I would hate moving targets under my fingers.

Title: How should a developer reject impossible requirements?

Body:
Here's the problem I'm facing:

Quote From Project Manager:

Hey Spark, I'm assigning you the task of developing a framework that could be used for many different iOS applications. Here are the requirements:

It should be able to detect the thickness of the thumb or fingers being used to manipulate the UI.

With this information, all elements of the UI should be arranged & sized automatically.

For a larger thumb, elements should be arranged nearer the center of the screen.

For a smaller thumb, elements should be arranged nearer the corners of the screen.

For a larger thumb, all fonts should be smaller. (We're assuming an adult in this case.)

For a smaller thumb, all fonts should be larger. (We're assuming a younger person in this case.)

Summary:

This framework is required for creating user-friendly user interfaces programmatically. The framework should be developed in such a way that we can use for as many projects as needed, so it must also be very developer-friendly.

I am the developer given this task, so my questions are as follows:

How can I explain that these requirements are a little ridiculous?

How can I explain that it would be better to concentrate on developing actual projects?

How can I explain that even if this were possible, I wouldn't recommended developing such a thing?

How do I say NO to this project politely, gently, and respectfully?

How can I explain that even for a developer with 3 years of experience, this might not be possible?


问:
c++ Model View Presenter: Where to construct presenter?
I'm using the Model View Presenter (MVP) pattern as described in The Humble Dialog Box paper (pdf) with an MFC project.  I'm sure the issue is the same with most GUI toolkits.

The thing that's bothering me is the concrete view (i.e., the dialog class) is creating not only the presenter but also the services that the presenter needs.  Is that normal?  Why does the view need to know what services the presenter needs?  What I'm thinking is that I should dependency inject the presenter into the dialog class.

The main control for the application is a class derived from CWinApp.  So should I construct services and presenter in this class and then inject them into the dialog class?

Although how would I dependency inject the presenter into the dialog class when the presenter needs a reference to the view class in it's constructor?

MyPresenter(IView *view, MyService *service);

Also how about if the main window spawns off a popup window, where should the details for that windows presenter and services get constructed?

Since this is C++ I don't think I'd be interested in any kind of DI framework.

UPDATE

One idea I had was to construct the presenter with a null view, constructor inject the presenter into the dialog class, and then in the constructor of the dialog class call a SetView(IView *view) method on the presenter with this where this would be the dialog class (which derives from IView).  So:

```<code>MyApp::Start()
{
  SomeService *service = new SomeService();
  MyPresenter *presenter = new MyPresenter(null, service);
  MyDialog *dialog = new MyDialog(presenter);
  ...
}

MyDialog::MyDialog(MyPresenter *presenter):
 presenter_(presenter)
{
  presenter_->SetView(this);
}
</code>```

Seems a little kludgy but keeps service construction out of the Dialog class.  The null view seems a little dangerous.  An alternative would be to actually construct a NullView class that had empty method bodies and then pass that into the presenter constructor.

答:
Perhaps a better solution is to use a factory class or method that knows how to build a presenter? The view would pass itself to the factory method and store the return value in it's presenter member.

This decouples information about how a presenter is constructed (dependencies on services or whatever) from the view itself.


答:
If you are worried about getting in trouble for being given impossible requirements, then the best choice is to tell them immediately that it is impossible.  The longer you let them build a business plan on an impossible project the more likely they are to blame you for the failure of the project.

Above all, try not to worry about things that are not your fault, we all have enough to worry about that we do have the ability to control.  If somebody were to hold you responsible for such a project failure then it is injustice against you.  Do you believe in Karma?


问:
Include all php files in one file and include that file in every page if we're using hiphop?
I understand that in normal php if we're including a file we're merging the source of it in the script and it would take longer for that page to be parsed/processed but if we're using HipHop shouldn't it be ok to just create one single php file and include every file in it (that contains some class) and every page which needs those classes (in separate file each) can just include one single php file?

Would this be ok in presence of HipHop?

答:
Correct way to handle this situation is using spl_autoload_register method to register your custom method that will be invoked every time a class is used in your file which is not yet declared.

In the implementation of this method you can do a dynamic include based on the class name. It is also supported in HipHop

http://www.php.net/manual/en/function.spl-autoload-register.php


答:
First of all, getting list of mutual friends is fairly easy and fast operation regardless of which solution you choose. It's just get all user A friends, get all user B friends and intersect the results.

Many RDBMSes implement that natively using INTERSECT, some of NoSQL stores also have set intersection commands (eg. SINTER in Redis).

Another thing is the performance of graph DBs isn't that great. Of course they advertise improvement of "1000x or more compared to relational DBs". However, this is improvement for generic graphs and generic graph algorithms. They give you much more flexibility, but if you have only few types of relations, dedicated code built on top of RDBMS or NoSQL will be more efficient.

Title: Which database should I use to manage relationship?

Body:
I need 2 capabilities:

calculating mutual friends distinguishing between different types of edges, (e.g. FRIEND, ENEMY and other)

getting relationships distinguishing between different types of edges as over

My problem is speed: If I use a database as MySQL, I can get thousands of relationships in few moments, but if I need to calculate mutual friends, it costs a lot for my server, doesn't it?

I've about 100,000 accounts on my site, and I want to introduce a relationship system, but obviously I have to decide the right way to develop it. Do you have any idea?


问:
Headaches using distributed version control for traditional teams?
Though I use and like DVCS for my personal projects, and can totally see how it makes managing contributions to your project from others easier (e.g. your typical Github scenario), it seems like for a "traditional" team there could be some problems over the centralized approach employed by solutions like TFS, Perforce, etc. (By "traditional" I mean a team of developers in an office working on one project that no one person "owns", with potentially everyone touching the same code.)

A couple of these problems I've foreseen on my own, but please chime in with other considerations.

In a traditional system, when you try to check your change in to the server, if someone else has previously checked in a conflicting change then you are forced to merge before you can check yours in. In the DVCS model, each developer checks in their changes locally and at some point pushes to some other repo. That repo then has a branch of that file that 2 people changed. It seems that now someone must be put in charge of dealing with that situation. A designated person on the team might not have sufficient knowledge of the entire codebase to be able to handle merging all conflicts. So now an extra step has been added where someone has to approach one of those developers, tell him to pull and do the merge and then push again (or you have to build an infrastructure that automates that task).

Furthermore, since DVCS tends to make working locally so convenient, it is probable that developers could accumulate a few changes in their local repos before pushing, making such conflicts more common and more complicated.

Obviously if everyone on the team only works on different areas of the code, this isn't an issue. But I'm curious about the case where everyone is working on the same code. It seems like the centralized model forces conflicts to be dealt with quickly and frequently, minimizing the need to do large, painful merges or have anyone "police" the main repo.

So for those of you who do use a DVCS with your team in your office, how do you handle such cases? Do you find your daily (or more likely, weekly) workflow affected negatively? Are there any other considerations I should be aware of before recommending a DVCS at my workplace?

答:
When I worked on a team that used git, the rule of thumb was this: work on a private branch, then, when you are ready to make your work available to the rest of the team, rebase your branch onto master before you push. (Then validate your branch.)

This strategy meant that master was a linear series of commits, and that all of the integration issues were repaired on branches before they were public.


问:
CPU Architecture and floating-point math
I'm trying to wrap my head around some details about how floating point math is performed on the CPU, trying to better understand what data types to use etc.

I think I have a fairly good understanding of how integer math is performed. If I've understood correctly, and disregarding SIMD, a 32-bit CPU will generally perform integer math at at least 32-bit precision etc.

Is it correct that floating-point math is dependent on the presence of a FPU? And that the FPU on the x86 is 80-bit, so floating point math is performed at this precision unless using SIMD? What about ARM?

答:
Many times, operations like floating point and memory management are encoded in a way that they can be "trapped".  This means that the system can be configured to either use hardware or automatically branch to a software implementation.  In the case of software, the implementation can be anything, although most manufacturers supply libraries that follow accepted standards (IEEE-754 in the case of floating point).  In many systems, when a floating-point unit or other chip is installed, the instruction execution is automatically deferred to the new chip, so no software reconfiguration is necessary.

As I understand it, the ARM architecture does something very similar to the x86, with floating-point instructions that trap to software emulation if no FPU hardware is found.


问:
What common programming problems are best solved by using prototypes and closures?
As much as I understand both concepts, I can't see how can I take advantage of JavaScript's closures and prototypes aside from using them for creating instantiable and/or encapsulated class-like blocks (which seems more of a workaround than an asset to me)

Other JS features such as functions-as-values or logical evaluation of non-booleans are much easier to fall in love with...

What common programming problems are best solved by using propotypal inheritance and closures?

答:
Closures are great for asynchronous logic.

It's mainly about organization of code for me. Having a bunch of local functions to split up what the code is doing is nice.

```<code>create: function _create(post, cb) {
    // cache the object reference
    var that = this;

    function handleAll(err, data) {
        var rows = data.rows;

        var id = rows.reduce(function(memo, item) {
            var id = +item.id.split(":")[1];
            return id > memo ? id : memo;
        }, 0);
        id++;

        var obj = {
            title: post.title,
            content: post.content,
            id: id,
            // refer to the object through the closure
            _id: that.prefix + id,
            datetime: Date.now(),
            type: "post"
        }

        PostModel.insert(obj, handleInsert);
    }

    // this function doesn't use the closure at all.
    function handleInsert(err, post) {
        PostModel.get(post.id, handleGet);
    }

    // this function references cb and that from the closure
    function handleGet(err, post) {
        cb(null, that.make(post));
    }

    PostModel.all(handleAll);
}
</code>```

Here's another example of a closure

```<code>var cachedRead = (function() {
    // bind cache variable to the readFile function
    var cache = {};

    function readFile(name, cb) {
        // reference cache
        var file = cache[name];
        if (file) {
            return cb(null, file);
        }

        fs.readFile(name, function(err, file) {
            if (file) cache[name] = file;
            cb.apply(this, arguments);
        });
    }

    return readFile;
})();
</code>```

And another example

```<code>create: function _create(uri, cb, sync) {
    // close over count
    var count = 3;

    // next only fires cb if called three times
    function next() {
        count--;
        // close over cb
        count === 0 && cb(null);
    }

    // close over cb and next
    function errorHandler(err, func) {
        err ? cb(err) : next();
    }

    // close over cb and next
    function swallowFileDoesNotExist(err, func) {
        if (err && err.message.indexOf("No such file") === -1) {
            return cb(err);
        }
        next();
    }

    this.createJavaScript(uri, swallowFileDoesNotExist, sync)

    this.createDocumentFragment(uri, errorHandler, sync);

    this.createCSS(uri, swallowFileDoesNotExist, sync);
},
</code>```

The alternative to using closures is currying variable into functions using f.bind(null, curriedVariable).

Generally though, asynchronous programming logic uses callbacks and manipulating state in callbacks either relies on currying or closures. personally I prefer closures.

As for uses of prototypical inheritance, it allows OO? Does prototypical inheritance really need to do more then that for it to be considered "useful". It's an inheritance tool, it allows inheritance, that's useful enough.

Body:
Closures are great for asynchronous logic.

It's mainly about organization of code for me. Having a bunch of local functions to split up what the code is doing is nice.

create: function _create(post, cb) {
    // cache the object reference
    var that = this;

    function handleAll(err, data) {
        var rows = data.rows;

        var id = rows.reduce(function(memo, item) {
            var id = +item.id.split(":")[1];
            return id > memo ? id : memo;
        }, 0);
        id++;

        var obj = {
            title: post.title,
            content: post.content,
            id: id,
            // refer to the object through the closure
            _id: that.prefix + id,
            datetime: Date.now(),
            type: "post"
        }

        PostModel.insert(obj, handleInsert);
    }

    // this function doesn't use the closure at all.
    function handleInsert(err, post) {
        PostModel.get(post.id, handleGet);
    }

    // this function references cb and that from the closure
    function handleGet(err, post) {
        cb(null, that.make(post));
    }

    PostModel.all(handleAll);
}

Here's another example of a closure

var cachedRead = (function() {
    // bind cache variable to the readFile function
    var cache = {};

    function readFile(name, cb) {
        // reference cache
        var file = cache[name];
        if (file) {
            return cb(null, file);
        }

        fs.readFile(name, function(err, file) {
            if (file) cache[name] = file;
            cb.apply(this, arguments);
        });
    }

    return readFile;
})();

And another example

create: function _create(uri, cb, sync) {
    // close over count
    var count = 3;

    // next only fires cb if called three times
    function next() {
        count--;
        // close over cb
        count === 0 && cb(null);
    }

    // close over cb and next
    function errorHandler(err, func) {
        err ? cb(err) : next();
    }

    // close over cb and next
    function swallowFileDoesNotExist(err, func) {
        if (err && err.message.indexOf("No such file") === -1) {
            return cb(err);
        }
        next();
    }

    this.createJavaScript(uri, swallowFileDoesNotExist, sync)

    this.createDocumentFragment(uri, errorHandler, sync);

    this.createCSS(uri, swallowFileDoesNotExist, sync);
},

The alternative to using closures is currying variable into functions using f.bind(null, curriedVariable).

Generally though, asynchronous programming logic uses callbacks and manipulating state in callbacks either relies on currying or closures. personally I prefer closures.

As for uses of prototypical inheritance, it allows OO? Does prototypical inheritance really need to do more then that for it to be considered "useful". It's an inheritance tool, it allows inheritance, that's useful enough.


答:
Closures are what makes functions as values useful. When you are passing the function, you almost certainly need it to take some context along. Which is exactly what closures do.

Prototypes are just a simpler version of class inheritance. Instead of having instances and classes (represented by special kind of instances in dynamic languages anyway), you have just instances and the prototype is the class (and it's prototype is the base class). So they basically solve the same problems, just the prototypes are easier to implement (that's why JavaScript chose them), somewhat harder to use (well, just lack of syntactic sugar) and for better or worse easier to abuse.

Title: What common programming problems are best solved by using prototypes and closures?

Body:
As much as I understand both concepts, I can't see how can I take advantage of JavaScript's closures and prototypes aside from using them for creating instantiable and/or encapsulated class-like blocks (which seems more of a workaround than an asset to me)

Other JS features such as functions-as-values or logical evaluation of non-booleans are much easier to fall in love with...

What common programming problems are best solved by using propotypal inheritance and closures?


答:
These requirements are not silly, stupid or ridiculous. This is in fact very important problem for users of touch screens, that people with larger fingers have it very difficult to pinpoint the target, which is often not understood by little-fingerers.

However, if you find this requirements impossible to implement because device's sensors are not able to measure finger size, just simply write this so: Unfortunatelly, currently available devices do not support such functionality


答:
If you understand C datatypes - it can support following formats:

The number of bits is distributed as : {Sign + Exponent + Significand }

float   -which is 32 bits distributed as 1 + 8  + 23.

dbouble -which is 64 bits distributed as 1 + 11 + 52.

Extended double - which is 80 bits dist. as 1 + 15 + 64.

So the extended double with 80 bits precision is the largest length float that can be natively supported by C in x86. Remember, that if your variable is float (32 bits) it still has precision equivalent to 32 bits not as per 80 bits in final storage. However, in most CPUs, the ALUs and FPUs are usually larger than native word length so that intermediate results do not overflow.

To support any precision better than above, additional software support is required. It is possible to create such higher precision arithmetic (e.g. cryptographic routines that generates arithmetic which are anything from 128 to 1024 bits; but this additional support is generated from software.)

Title: CPU Architecture and floating-point math

Body:
I'm trying to wrap my head around some details about how floating point math is performed on the CPU, trying to better understand what data types to use etc.

I think I have a fairly good understanding of how integer math is performed. If I've understood correctly, and disregarding SIMD, a 32-bit CPU will generally perform integer math at at least 32-bit precision etc.

Is it correct that floating-point math is dependent on the presence of a FPU? And that the FPU on the x86 is 80-bit, so floating point math is performed at this precision unless using SIMD? What about ARM?


问:
What's the point of adding Unicode identifier support to various language implementations?
I personally find reading code full of Unicode identifiers confusing. In my opinion, it also prevents the code from being easily maintained. Not to mention all the effort required for authors of various translators to implement such support. I also constantly notice the lack (or the presence) of Unicode identifiers support in the lists of (dis)advantages of various language implementations (like it really matters). I don't get it: why so much attention?</p>

答:
Of course, every modern compiler must deal with Unicode source code today. For example, string constants may need to contain Unicode characters. But once this is achieved, why not allow unicode identifiers also? It's no big deal unless your compiler code depends on characters being 7-bit codes.

But the OP is right insofar: It is now possible that a Hindi speaking Indian must maintain code with russian identifiers and arabic comments. What a nightmare for the poor Chinese who is supposed to do the quality check and who can't read any of the above 3 alphabets!

Hence, it is now an organizational tasks to make sure a programs identifiers and comments are written in a common language. I can't help it but I think this is going to be english for some time to come.


答: What you do is treat it seriously and come back with an estimate of how long it would take to do and make sure the estimate is very high and very detailed so they can't dispute the high numbers. Once you have shown it won't be economical to do they will leave you alone. Make sure to point out whci specific tasks are not currently supported by the hardware and may or may not even be feasible to do. Do forget to add costs for any sort of specialists additional people you might need for a project of this magnitude. </p>


问:
Where can I find inspiration for a good user interface?
I've got a mental block as far as desigining the main screen interface for a desktop application that I'm currently upgrading. When I first developed this program the screen resolution was 640 X 480. Today there are multiple screen resolutions out there.

Where can I find ideas for a good main screen layout for a desktop application?

答:
One tip I have often heard is to look at designs you like for inspiration.  This is not isolated to just say desktop applications, but should extend to art, architecture, web, photography, products, etc.

This will help you build a sense for what good design is and will help you in ht long run design applications that are pleasing to the eye and user friendly.

If you prototype your design you can get some help from users or other developers to take it for a spin while gathering feedback.  Not just what the say, but what they do.  (example: people say they don't like cluttered isles at Walmart, but they literally lost more than $1B in sales when thy removed the clutter)


问:
Are Get-Set methods a violation of Encapsulation?

Possible Duplicate:

  When are Getters and Setters Justified

In an Object oriented framework, one believes there must be strict encapsulation. Hence, internal variables are not to be exposed to outside applications.

But in many codebases, we see tons of get/set methods which essentially open a formal window to modify internal variables that were originally intended to be strictly prohibited. Isn't it a clear violation of encapsulation? How broadly such a practice is seen and what to do about it?

EDIT:

I have seen some discussions where there are two opinions in extreme: on one hand people believe that because get/set interface is used to modify any parameter, it does qualifies not be violating encapsulation. On the other hand, there are people who believe it is does violate.

Here is my point. Take a case of UDP server, with methods - get_URL(), set_URL(). The URL (to listen to) property is quite a parameter that application needs to be supplied and modified. However, in the same case, if the property like get_byte_buffer_length() and set_byte_buffer_length(), clearly points to values which are quite internal. Won't it imply that it does violate the encapsulation? In fact, even get_byte_buffer_length() which otherwise doesn't modify the object, still misses the point of encapsulation, because, certainly there is an App which knows i have an internal buffer! Tomorrow, if the internal buffer is replaced by something like a packet_list the method goes dysfunctional.

Is there a universal yes/no towards get set method? Is there any strong guideline that tell programmers (specially the junior ones) as to when does it violate encapsulation and when does it not?

答:
Suppose you have a 'Complex' class. It has four getters: real, imaginary, magnitude, and angle. Clearly, in any reasonable representation, two of these functions simply return the value of a private member variable. What encapsulation means is that it doesn't matter which two of these methods is "simple" and which one does a calculation.

(one could imagine a mutable complex class that also has setters for these. Again, clearly two of them simply directly set a private member variable.)


问:
What is jQuery and JavaScript's role in MVC?
I'm not sure I understand the role of jQuery/JavaScript in MVC. I've found an article about it on A List Apart, but it doesn't clear anything up for me.

Does it bridge the communication between the View and the Controller, or does it do something else?

答:
Javascript is not related to the zend framework, or anything you use on the server. It runs in the browser. (Yes it could run anywhere but let's simplify)

Let's say you have a desktop application that is programmed using the MVC pattern and at some point it needs to make a request to a server to fetch some data. To fulfill the request, the server might be using MVC pattern or it might not, it doesn't relate in any way to the desktop application.

Javascript works the same way but traditionally is more dependent on making requests to a web server than a desktop application. But it doesn't have to be, with html5 offline capabilities, file reading and localstorage you can make a desktop style javascript app that doesn't use any server at all but still runs in the browser. Now, you could design the javascript app using MVC or whatever you see fit but it doesn't relate to what any server you might be making requests to is using.

So to answer your question, there is no role for javascript in zend MVC. The zend MVC controller is only invoked by HTTP requests, while if you were to use MVC in javascript, the controller in javascript MVC would be invoked by various user actions in the app. And jQuery is just a bunch of javascript, so it applies for jQuery as well.

OwnerDisplayName: Esailija


答:
Java means two different things:

the Java language - this includes the language, with its syntax, rules, features and overall semantics

the Java platform - this includes the runtime (JVM), the whole standard library and a number of popular frameworks/libraries. Note there are also other Java "runtimes" such as being executed as JavaScript after crosscompilation through GWT, or Java on Android, which is also runs in a different runtime

The Java language and Scala both run on the same platform. AFAIK Scala can call down to Java code quite easily, so if there is any real interest in learning Java to understand/leverage Scala, then it is to understand how this works and how you can best use Java code from within a Scala app. As a language, Java is unlikely to teach you anything C# wouldn't have taught you by now (I assumed from your profile you have some C# experience).

This question's .NET-analogy would be:

Do you need to know C# / VB.NET before trying F#?

In either case, the answer is a pretty firm "No."

Title: Do you need to know Java before trying Scala

Body:
I'm interested in learning Scala. I've been reading a lot about it, but a lot of people value it because it has an actor model which is better for concurrency, it handles xml in a much better way, solves the problem of first class functions.

My question is do you need to know Java to understand/appreciate the way things work in Scala?
Is it better to first take a stab at Java and then try Scala or you can start Scala with absolutely no java backround?


答:
My response would be that I would start looking into some of these untried technologies and let them know if it is even possible. Based on those discoveries, a potential development plan can be started.

I don't think you'll be able to tell one person's thumb from someone elses, but you may be able to get enough dimensions from the fingers to know when they're using the thumb. The real problem is because of the angle of the thumb it may not touch any more space on the screen than others. No one ever uses a phone with their thumb and places it flat on the screen like you're having your thumb print taken.

Leave the company. Figure out how to do it. Sell it for a lot more money than you're making now.


问:
How should we deal with multiple transaction-report requests?
We are developing a system for the retail market and of its features will enable clients (actually consumer clubs) to go through all transactions made by end-clients.

One of the ways to get this information will be via an API.

The idea is that there will be requests for reports with a start date and an end date, and a response will have all the transactions between those dates.

We worry that some reports will be very large, and that some clients will repeatedly request for reports, in this case the DB and CPU will be very overloaded.

The same server that is going to service those requests will also take care of the actual retail transactions (received by proprietary devices) and of the Web application.

We are not sure about how to limit the report requests from the API so that it won't affect the system too much.

So, how should we deal with this scenario? any thoughts?

EDIT:

just to make it clear:
When I mentioned proprietary devices I meant "On-Location" devices which are used during sales with end-clients, this means that these requests shouldn't get delayed, and this is the main concern.

One more question : Some people here suggested the use of prioritized threads, i.e. - giving lower priority to the threads retrieving the reports, is this a good idea?

答:
There's something called a "waterfall diagram" (not to be confused with waterfall software development methodology). It has time on the X axis, and activities on the Y axis, like this:

```<code>Activity A---->|
               |--- Activity B --->|
                                   | --- Activity C --->|
</code>```

There are tools to get this, but basically it's a matter of logging the start and end times of the various activities of a transaction, such as fetching stuff from the DB, sending stuff to the client, waiting for the client to execute the code, etc.

The key is that all these steps are sequential, adding up to the total time.

This can tell you if there is any unnecessary delay, such as is caused by one thread or process waiting on another without absolutely needing to, across multiple machines and connections.

If you use a technique like this, you can quickly get to the bottom of any unnecessary latencies.

Body:
There's something called a "waterfall diagram" (not to be confused with waterfall software development methodology). It has time on the X axis, and activities on the Y axis, like this:

Activity A---->|
               |--- Activity B --->|
                                   | --- Activity C --->|

There are tools to get this, but basically it's a matter of logging the start and end times of the various activities of a transaction, such as fetching stuff from the DB, sending stuff to the client, waiting for the client to execute the code, etc.

The key is that all these steps are sequential, adding up to the total time.

This can tell you if there is any unnecessary delay, such as is caused by one thread or process waiting on another without absolutely needing to, across multiple machines and connections.

If you use a technique like this, you can quickly get to the bottom of any unnecessary latencies.


问:
Would you put your Stack Overflow profile link on your CV / Resume?
If applying for a new job, would you put your Stack Overflow profile link on your resume?

This would show the employer you're an active member of the development community and also provide an insight into your knowledge + how well you convey your ideas.

However it would feel a bit gimmicky to me?

答:
As I commented on Josh K's answer (a good one to take into consideration mind you), it depends on the type of content that you put in via your stackoverflow account. You can generalize that to the type of content present on your identifiable internet presence. I would probably not do it, not because it is a bad idea (nor I feel my content is inapropriate), but because I'm already including my linkedin profile and tech blog in my CV.

Potential employers can then use that to discern what I've posted on SO, ServerFault or say, cstheory.stackexchange or even slashdot if they so wish. I try to create mostly good content but there are a couple of WTFs here and there. I don't worry about them. If my content however contained a high ratio of flamewards and LOLZ, then I would be worried.

I used to have one like that before under a pseudonym (younger, stupider days), but that has been completely replaced with more professional content under my actual name. The older one can still be found if one is really persistent, but then, unless I'm applying for, I dunno, a top secret gig or something like that, I would not be happy if an employer goes to that extreme of finding my much older content.

Neither would I accept to continue an interview or work with such a company. Probabilistically speaking, I doubt that such a thing is a common occurrence for employers worth working for (except for jobs with valid reasons to perform extensive background checks.)

So, it is a personal call whether to include a SO's profile on your CV. It depends on what type of content you have. My personal feeling is that I would prefer to have a well-maintained linkedin profile or tech blog, have it with links to other tech-oriented profiles of yours, and have that (your linkedin profile or a technical blog) included in your CV.

ContentLicense: CC BY-SA 2.5


问:
What are safe keys to remap in vim?
So far I've been trying to use Vim in as vanilla a configuration as possible, so as to save myself hassle when moving between machines. However, there are a few things I'd really like to bind keys, such as to shorten "_diwP which I use often to delete the word under the cursor and replace it with one from the clipboard. Are there any particular keys that are conventionally reserved for user-defined mappings? The point of this question is mostly that I would like to avoid hassle later on when I decide to install some plugin or take my configuration files to vim on another OS and find that my key mappings clash with something else.

答: I have a french keyboard. I use é, è, à, ù, µ, §, £, ç ...

Title: What are safe keys to remap in vim?


答:
All keys are safe to remap in Vim. However, there are two types of mappings: recursive and non recursive.

a) Recursive:

If you remap for example,

```<code>nmap x dd
</code>```

x deletes the line instead of one character

you will have effectively lost the x key for future mappings, as well as overwritten the delete character function. Were sometime in the future some plugin depend on that key, that could present a problem.

For example,

```<code>nmap <C-x> xxx
</code>```

will delete three lines instead of three characters, because it is effectively doing dddddd. This is a problem since effectively were some of your plugins to use the x (and they surely will) it will create problems (nasty ones).

b) Non recursive mapping

```<code>nnoremap x dd
</code>```

solves that problem in a way that it will assign dd to x so that upon your pressing x you delete a line instead of a character, but any future mapping

```<code>nnoremap <C-x> xxx
</code>```

will have the original x  on the right hand side functionality.

Always use nnoremap, inoremap ... the non-recursive mapping instead of nmap, imap and so on ... unless you have a very strong reason for doing the opposite.

Title: What are safe keys to remap in vim?

Body: So far I've been trying to use Vim in as vanilla a configuration as possible, so as to save myself hassle when moving between machines. However, there are a few things I'd really like to bind keys, such as to shorten "_diwP which I use often to delete the word under the cursor and replace it with one from the clipboard. Are there any particular keys that are conventionally reserved for user-defined mappings? The point of this question is mostly that I would like to avoid hassle later on when I decide to install some plugin or take my configuration files to vim on another OS and find that my key mappings clash with something else.

Body:
All keys are safe to remap in Vim. However, there are two types of mappings: recursive and non recursive.

a) Recursive:

If you remap for example,

nmap x dd

x deletes the line instead of one character

you will have effectively lost the x key for future mappings, as well as overwritten the delete character function. Were sometime in the future some plugin depend on that key, that could present a problem.

For example,

nmap <C-x> xxx

will delete three lines instead of three characters, because it is effectively doing dddddd. This is a problem since effectively were some of your plugins to use the x (and they surely will) it will create problems (nasty ones).

b) Non recursive mapping

nnoremap x dd

solves that problem in a way that it will assign dd to x so that upon your pressing x you delete a line instead of a character, but any future mapping

nnoremap <C-x> xxx

will have the original x  on the right hand side functionality.

Always use nnoremap, inoremap ... the non-recursive mapping instead of nmap, imap and so on ... unless you have a very strong reason for doing the opposite.


问:
Java code generation from class diagram
I'm on the way developing a Java application where user can provide a class diagram and get the corresponding Java code.

I don't know how can I let the user interactively draw a class diagram in Java. I am currently getting the required parameters like attributes, functions directly from the user, and then I render a class diagram for him. I show the class diagram on a jdialog.But when it comes to multiple class diagrams, it screws me. Is there a better way to do this?

This is an example of a class diagram, I need to generate this from a Java program, given the values and relationship.

答:
First point: this is fairly non-trivial. Second point: the fact that the Java environment makes the Java compiler directly available will help a lot in implementing this. I believe you should be able to collect most (all?) the information you need by walking the AST with the compiler tree API. At least from the looks of things, the part you'll care the most about will be the ClassTree interface. So, the basic idea would be to create your tree visitor, walk the tree, and collect information about the ClassTree objects you find.

Once you've collected the information, it becomes mostly a matter of drawing a nicely formatted result. If you have some funds available, I've heard good things about yFiles for Java (I should also mention that the same company's yWorks UML Doclet is supposed to do nearly what you're talking about, but from JavaDac comments rather than the source itself). There are, as you'd expect, lots of alternatives to that as well. I don't know enough about most (any?) of them to comment further on them though (I did use GraphViz once, but so long ago that I don't remember much, and what little I might remember is probably obsolete anyway).

Title: Java code generation from class diagram


问:
Unix as opposed to Windows (Java and C++)
Firstly I should explain the background. I am interested in high frequency trading programming roles. After looking at many job specs it is very clear that there is a big demand for programmers who have programmed Java and C++ on Unix as opposed to Windows.

My question is what are the differences a High Freq programmer would come across? It cannot be something in the language itself because syntactically they do not differ over OS? Therefore I thought it must be something which the programming language has to interface, resources etc?

Could anyone please help me out as I am trying to improve my C++/Java on Unix, in order to aim for this type of career?

ps I'm guessing part of this answer lies with the socket infrastructure on Unix?

答:
Transaction servers are mostly(but not only) Unix: Thats because Unix is highly stable,  and less resource hungry. A less important but not ignorable reason is legacy applications. You wouldnt want to move a stabe unix based transaction server to Windows.

But that doesnt necessarily mean that you have to program on Unix. Once I did a project on Oracle D2K . The app runs on Windows but the forms were stored on a Unix server.

If you are looking at C++ programming for high volum esystems , do pay a lot of attention to threading and exception handling, apart from socket programming. Learn whatever you can about application optimization. Few books teach you that.  Learn what you can from expereinced people and from your own experience.


问:
Rights and use of developed software
I have been working on a piece of software for a company, that they wish to resell.

There was an mail-based agreement upon a flat hourly rate for my work, and eager me chose to accept a rather low fee.

Due to the stress and tempo of the task, a direct contract was never formed or signed.

The software was developed locally on my machine, and I was pretty much alone with it, except by excellent help from StackOverflow when I got stuck.

Now, the software is nearing completion, I suddenly hear that they have hired a new developer to make the same piece of software as me, and that I was expected to resign within long.

Confused I ask around, and realize that the CEO of the company had informed the rest of the company that I was terminally ill and had cancer, and was expected to leave the company soon.

Since I'm perfectly healthy, this confused me even more, until I realized what was going on. When I confronted my boss with this, I was no longer seen as a member of the company, and I left the same day, never to return.

Later, I raised the question about my missing pay, since I had been working for quite a bit, and not received any payment for my software. I saw that they had already sold a fair copy of my software, and since it's not exactly sold cheap, the company should have plenty of gold to pay me.

The company refused, and said that they owned the software, and everything it contained.

That was a lot of drama, but my question is this:

Who has the rights to the software ?

The source code had my personal watermarks and copyrights inprinted, but they have since simply deleted it. The company claim that they have all the rights, because they have a website made about the product, where they write that they have "All rights reserved" in the bottom.

My instinct tells me that if a company buys a service like this, and then refuses to pay their developer, then they should not be allowed to keep, and much less resell the product.

I have not signed any agreements about giving the company the use of this product, I have made it in my own time and without help from the rest of the company.

This all takes place in Denmark, Europe, but I would guess that the rules about this is somewhat universal.

Im not the strongest person to legal-talk, so I might be wrong.

答:
You need to talk to a lawyer to get proper advice about this.

In general if you created it the copyright resides with you until you assign it to someone else.  My understanding is that if there is no contract then you can't have assigned them copyright.  In many countries if you haven't received any payment, of any kind, then there can not be a contract.

However, I am not a lawyer.  Free legal advice on the internet is worth exactly what you pay for it :-)

Title: Rights and use of developed software


问:
best and most used algorithm for finding the primality of given positive number
When I was in college and as a programming language learner I wrote program for finding out prime numbers but then I never mind the program performance in terms of speed. Now after long time just started solving the problems from projecteuler.net.

Now I wonder is there any best and most used algorithm for finding the primality of a given positive number which produces the result fast?

Thanks

答:
For prime testing of very large numbers, there are probabilistic methods:

http://en.wikipedia.org/wiki/Primality_test#Probabilistic_tests

Most popular primality tests are probabilistic tests. These tests use, apart from the tested number n, some other numbers a which are chosen at random from some sample space; the usual randomized primality tests never report a prime number as composite, but it is possible for a composite number to be reported as prime. The probability of error can be reduced by repeating the test with several independently chosen values of a...


问:
How should a developer reject impossible requirements?
Here's the problem I'm facing:

Quote From Project Manager:

Hey Spark, I'm assigning you the task of developing a framework that could be used for many different iOS applications. Here are the requirements:

It should be able to detect the thickness of the thumb or fingers being used to manipulate the UI.

With this information, all elements of the UI should be arranged & sized automatically.

For a larger thumb, elements should be arranged nearer the center of the screen.

For a smaller thumb, elements should be arranged nearer the corners of the screen.

For a larger thumb, all fonts should be smaller. (We're assuming an adult in this case.)

For a smaller thumb, all fonts should be larger. (We're assuming a younger person in this case.)

Summary:

This framework is required for creating user-friendly user interfaces programmatically. The framework should be developed in such a way that we can use for as many projects as needed, so it must also be very developer-friendly.

I am the developer given this task, so my questions are as follows:

How can I explain that these requirements are a little ridiculous?

How can I explain that it would be better to concentrate on developing actual projects?

How can I explain that even if this were possible, I wouldn't recommended developing such a thing?

How do I say NO to this project politely, gently, and respectfully?

How can I explain that even for a developer with 3 years of experience, this might not be possible?

答: It should not be too hard to tell your client that you cannot implement something your target platform does not allow you. But take a step back and ask yourself , what is the logic behind these rather riddiculous requirements? From what I can read they are very concerned about user-friendliness. Then ask them, dig a bit deeper till they say the same thing to you: "we want a user friendly interface". Then guide them into what is doable and what is not. Tell them that if they want an easy user interface there are easy (and cheaper ways) such as letting the user set the font/icon size (I assume that i possible on the IoS). Maybe you can let the user control the font size/icon size and arrangement for the application through a settings tab? That should be easier (and more accurate!) than trying to guess the age of a person on the thumb size! The last thing your manager would want is unnecessary, bloated, hard-to-maintain code that achieves the same thing that the os already provides. Tell your client that users would prefer controlling the application rather than the application controlling them in ways that may infuriate them.</p>


答: You'll need to know how to use the various Unix profiling and performance management tools (everything from ps to dtrace), plus all the other development tools (shell scripting, Perl, awk, find, xargs...).  You'll need to know your way around the file system (like how to get performance counters from the /proc directory).  I haven't worked in that particular industry, but generally Unix positions depend on lot more on using generic command-line tools than GUI-based stuff.

Title: Unix as opposed to Windows (Java and C++)

Body:
Firstly I should explain the background. I am interested in high frequency trading programming roles. After looking at many job specs it is very clear that there is a big demand for programmers who have programmed Java and C++ on Unix as opposed to Windows.

My question is what are the differences a High Freq programmer would come across? It cannot be something in the language itself because syntactically they do not differ over OS? Therefore I thought it must be something which the programming language has to interface, resources etc?

Could anyone please help me out as I am trying to improve my C++/Java on Unix, in order to aim for this type of career?

ps I'm guessing part of this answer lies with the socket infrastructure on Unix?


答:
I once worked in a Java project in which we developed an ERP application that ran both on Linux and Windows. I developed on Linux (Java, Eclipse) but the main customers used it on Windows.

The Java code did not need any changes between Linux and Windows. The only difference I noticed was that the application ran much faster on Linux and a colleague of mine explained to me that the Linux file system is much faster than the Windows file system. Maybe this (performance) is one of the reasons why there is a big demand for developers who can work on a UNIX system.


问:
What methods to you use to promote programmer awareness in an API or custom architecture?
If you are developing your own architecture or heavily use anothers vendors API, how do you promote awareness to the programming staff? For example, say you use Infragistics controls for you C# winforms apps - the controls have boatloads of methods, some quirks, and a best way to use them for your application. How do you promote the knowledge transfer thru your programming staff? Wiki's? Email? Blogs?.</p>

答:
Use a combination of formats, appropriate for each knowledge function.

Blogs and RSS feeds can be used to announce updates, news items, etc.

Wikis can be used to document current standards, policies, processes, how-tos, APIs, etc. The content can be structured, given a table of contents and index, support the development of commentaries, provide versioning, dynamic updates, etc.

Forums/discussion boards can be used to work out issues of a technical or managerial nature.

Definitely allow tagging of content tagged for a variety of categories (data types, layer, functionality, bugs, etc).


答:
One very fast method of Rejecting a trial prime is to use that fact that all primes are of the form 6k +/- 1, where k is a positive integer. (2 and 3 excepted).

This means you can reject a number with only two tests (plus the trivial).

```<code>public static boolean checkPrime(long p)
{
   if (p==2 || p==3) return true;
   if ( (p+1) % 6 == 0 || (p-1) % 6 == 0 )
   {
      // p might be prime, worth checking
      return checkProbablePrime(p);
   }
   else
   {
     // p is not prime.
     return false;
   }
}
</code>```

Whether or not this is a good technique depends on the distribution of inputs.  If you expect a high percentage of composite numbers, then this is a quick way of eliminating them from contention.  It would be nice to eliminate the trivial branch at the top (==2, ==3) but that depends on the context of the inputs.  If your goal is to FIND primes, then you should skip this.

Title: best and most used algorithm for finding the primality of given positive number

Body:
When I was in college and as a programming language learner I wrote program for finding out prime numbers but then I never mind the program performance in terms of speed. Now after long time just started solving the problems from projecteuler.net.

Now I wonder is there any best and most used algorithm for finding the primality of a given positive number which produces the result fast?

Thanks

Body:
One very fast method of Rejecting a trial prime is to use that fact that all primes are of the form 6k +/- 1, where k is a positive integer. (2 and 3 excepted).

This means you can reject a number with only two tests (plus the trivial).

public static boolean checkPrime(long p)
{
   if (p==2 || p==3) return true;
   if ( (p+1) % 6 == 0 || (p-1) % 6 == 0 )
   {
      // p might be prime, worth checking
      return checkProbablePrime(p);
   }
   else
   {
     // p is not prime.
     return false;
   }
}

Whether or not this is a good technique depends on the distribution of inputs.  If you expect a high percentage of composite numbers, then this is a quick way of eliminating them from contention.  It would be nice to eliminate the trivial branch at the top (==2, ==3) but that depends on the context of the inputs.  If your goal is to FIND primes, then you should skip this.


问:
Where do other programming languages fit in Windows 8 development model?
Today, Windows applications can be developed in numerous languages and frameworks. But in the upcoming Windows 8, with the introduction of WinRT, the development model is going change at a large scale. So, where do other programming languages fit in this model?</p>

答:
The .NET Framework and the Common Language Runtime (CLR) is integrated
  into WinRT as a subplatform... WinRT supports XAML-based .NET Metro-style applications which are
  primarily written in C# and VB.NET. Although not yet officially
  supported, programs can also be written in other .NET languages.

Classes defined in WinRT components that are built in managed .NET languages must be declared as sealed... Members that interface with other language must have a signature with WinRT types or a managed type that is convertible to these.

Native C++ is a first-class citizen of the WinRT-platform.  The language has a number of extensions that enable integration with the platform and its type system.

The "Chakra" JavaScript engine which was developed for Internet Explorer 9 integrates with WinRT. That makes JavaScript a first-class citizen in the WinRT ecosystem.

http://en.wikipedia.org/wiki/Windows_Runtime


答:
I have some experience with code generation, significantly less with diagramming. I have a few suggestions:

I notice you use human readable text. I suggest googling for Inflector.java and choosing an appropriate implementation. This will also help with variable names for unlabelled relationships between classes (pluralization gives you List<Foo> foos and stuff like that).

I use UML diagrams, but I use an xml serialized form. The UML XMI stuff from OMG has been helpful to me. It's much easier to import/export the underlying information for UML diagrams than to lay them out yourself. This might not be applicable since you seem to want to do the diagramming portion yourself. Much has been written on laying out diagrams. I suggest you do some reading if you want to generate diagrams from source without resulting in a jumbled mess.

I use both antlr and StringTemplate. Starting with a good parser/grammar to read source is nice. StringTemplate is pretty nice for generating source code. I also use it at work for email templates. If you don't want to read source, suck in a jar or class file and go to town. I have a lot of code built around BCEL. You might want to look at ASM if you don't like BCEL.

Title: Java code generation from class diagram

Body:
I'm on the way developing a Java application where user can provide a class diagram and get the corresponding Java code.

I don't know how can I let the user interactively draw a class diagram in Java. I am currently getting the required parameters like attributes, functions directly from the user, and then I render a class diagram for him. I show the class diagram on a jdialog.But when it comes to multiple class diagrams, it screws me. Is there a better way to do this?

This is an example of a class diagram, I need to generate this from a Java program, given the values and relationship.