问:
Functions returning either "OK" or "error message" instead of procedures
I have joined writing middle-size multi-purpose database application as co-lead. It currently has about 150 tables (and growing) and overall functionality you can imagine as very small ERP.

At many places in code, functionalities which would normally belong into procedures (I mean functions without return value) like DeleteAttachment or SaveRecord are put into functions with return value reporting their exit status in string. They return either "OK" on success or messages like "Deletion failed because ......." or "Insufficient privileges for .......".

At the end, often the end user is presented with message they provided. On one hand, this is effective mechanism of tracing of potential problems. On the other hand, I'm not sure whether I should encourage this approach of writing the inner business logic.

I understand that putting non-fatal problems into exceptions is also not very good way to go (EInsufficientUserPrivileges, ERecordAlreadyExists). Should we stick with current approach or is there some other which is more suitable for applications using a many checks and business logic?

答:
To draw the line between exceptions and return values, I would try to stick to the following:
  - Anytime an instruction breaks the expected flow of execution, you expect an error to be thrown.
  - If the expected function of procedure may have different outcomes, you will want to work with return values.

In the examples that you are stating, it seems very clearly that the expected instruction is not performed. Error messages like: "Deletion failed", or "Insufficient privileges" end up with your action being void. Therefore, you would clearly expect an error to be thrown. In this context, fatal is equivalent to "your instruction could not be performed". On the other hand, an exception does not necessarily have to be fatal. You may well handle it, and proceed with other instructions (other deletions, insertions, or whatever needs to be done). This is what you can achieve with a catch block.

Another thing: returning a string with "OK" is not good practice. Use boolean values instead. Now again, if you want return values to be "OK" or "Error message", a boolean will not let you achieve that. An exception will let you put an error message, and any detail you want to store about the error that has happened. You could for example, if a user is denied access, store the user name, the priviledges that he has, and the record that he tried to access in an exception. You could then use this information as you catch the error to generate a short error message to the user, and a more detailed message for your error log.


问:
Is Java easy decompilation a factor worth considering
We are considering the programming language for a desktop application with extended GUI use (tables, windows) and heavy database use.
We considered Java for use however the fact that it can be decompiled back very easily into source code is holding us back.

There are of course many obfuscators available however they are just that: obfuscators.
The only obfuscation worth doing we got was stripping function and variables names into meaningless letters and numbers so that at least stealing code and renaming it back into something meaningful is too much work and we are 100% sure it is not reversible back in any automated way.

However as it concerns to protecting internals (like password hashes or sensible variables content) we found obfuscators really lacking.

Is there any way to make Java applications as hard to decode as .exe counterparts?

And is it a factor to consider when deciding whether to develop in Java a desktop application?

答:
Yes, you can make Java programs arbitrarily hard to decode. It depends on how much you want to do it and how much time and skill you have in pursuing this goal.

First, obfuscation is pretty good. Apart from mangling names it is possible to distort the code flow to the point where making sense of how a program works, what algorithm it uses and how it manipulates its data is just as hard as an optimised C++ program.

Second, it is very straightforward to disguise key data. As good developers of internationalised and configurable software you already store your data separately from your code, in resource files or something similar. The C++ programmer does something similar. You can easily encrypt that data using an algorithm and key buried deeply in the code.

Although my experience of this is in languages other than Java, you can arrange for chunks of code to be stored in encrypted form and decrypted when loaded into memory.

In these days of continuous Internet connection you can retrieve the code and keys you need dynamically from the 'net, and protect them with certificates. That's what Microsoft does with its store apps.

All of this is perfectly possible, and the game developers are doing it right now. On the other side are legions of hackers just waiting for the next release to wheel out their in-memory debugging tools and be the first to announce a crack.

You should wish that your software becomes well-known enough and valuable enough to attract this kind of attention. I have always focused first on solving the problem that no-one has heard of my software. If I am ever fortunate enough to have millions of hackers trying to break my programs, I am sure I shall have the resources to give them a good run.

ContentLicense: CC BY-SA 3.0


问:
Environment-aware Code
There are situations where the deployed environment (development, test, or production, for example) might dictate the outcome of certain actions.

For example, perhaps a successful "user registration" process will send a notification email to the new user.  Environment-specific actions:

Development:  Do not actually send the email.  Email logs will provide enough for developers.

Test:  Send all emails to some testEnvironment@domain.com inbox and not to the user's address.

Production:  Send the email to the user.

I have listed three possible solutions below.

CurrentEnvironment configuration value

One way of solving this, which I have seen a lot, is to have some configuration value (whether it be in some xml config file or in the database) such as CurrentEnvironment which specifies the current environment in which the system is deployed to.  This would require case/if checks in code to determine the desired action:

```<code>if(CurrentEnvironment == Environment.Test)
{
    // Send all emails to some testEnvironment@domain.com inbox.
}
else if(CurrentEnvironment == Environment.Production)
{
    // Send the email to the user.
}
</code>```

This is not a maintainable solution in my opinion.

Wipe all email addresses

Another method is to run a change script, once restoring a database, to do the following:

Remove all user email addresses (in development),

Replace all user email addresses with testEnvironment@domain.com (in test)

This is an extra step in the release process which, if missed, could have some dangerous results.  Additionally, this solution only fixes the email problem.  There are perhaps many other situations where the environment matters.

Config transformation

Another idea is to use web.config transformations.  This way the config can be different for different environments.  For example, we will have the following configs:

```<code> web.config
   web.Development.config
   web.Test.config
   web.Production.config
</code>```

The transformation can then use different "providers" or set certain attributes according to the environment.  For example, an overrideDeliveryAddress can be set in the web.Test.config:

```<code><EmailService>
  <providers>
    <add
      name="EmailServiceProvider"
      type="CustomProviders.EmailServiceProvider, CustomProviders"
      smtp="smtp.domain.com" password="xyz"
      overrideDeliveryAddress="testEnvironment@domain.com"
      enabled="true"
    />
 </providers>
</EmailService>
</code>```

This solution requires much more work, but is more maintainable and less invasive.  Code is now environment-oblivious.

What other ways can the above be achieved?  Should code EVER be environment aware?

答:
I would propose an approach based on Dependency Injection and Null Objects. If you let your configuration define which object should be used for a specific task in each environment, then you can define specific behaviors within these objects. Then you use a Factory to initialize your objects depending on the environment.

I will use the mail as an example, but this approach can be applied in many other contexts: logs, error messages, communications with external API, etc... A null mailer will be an object that has the same interface as your usual mailer, and will simply ignore the send mail instructions. The objects that need to send emails will have a mailer parameter that is initialized at object instantiation: in your production environment, you mailer will be your usual mailer. In your test environment, your mailer will be you null ("do nothing") mailer.

To manage the instantiation of objects depending on the environment you work in, build a factory object that reads your configuration file and return the mailer (logger, api library...) depending on what is specified there. You may have a configuration file for each environment.

Title: Environment-aware Code


问:
Does agile approach support taking a task from a team?
Can customer take one of tasks during the planning meeting, which was already assigned to this team, and put it to another team? For example because a customer think that the other team will be faster in implementing it?
Is it normal for some agile methodologies? If yes, could you, please, provide me with the source of this information(book or web link), because I do not know how to handle it, especially because of team spirit: such a thing can make people in team demotivated and also there can origin some tenses in between these two teams...

It is part of some agile methodology and what are the constraints to make this thing?

答:
There is not really an agile 'rulebook' with do's and dont's. People are encouraged to follow common sense based upon some general guidelines.

To answer your question: in my point of view it depends on what you mean by "task".

If you mean implementing a certain functionality, it is up to the Product Owner to decide if functionality needs to be developed or not, and in which timeframe. If he sees that another team will deliver faster he has the option to give it to another team. I am not claiming that it is a good idea to do so in case of existing problems between teams and it will clearly not motivate the first team.

If you mean a pure technical task part of a userstory, it is up to the team to decide how to implement it.


问:
How to measure the quality of my use cases?
When I'm coding something I know that there are many ways to see if my code is good or not. First is testing: I can do unit tests or even test the software by myself and see that it works or not. After getting it working, I can analyze the coupling of the code and so on to refactor and make it better. In that sense, I'm confident when coding because I have a way to know if what I did works or not and ways to think it better if it doesn't work.

When designing the software though I'm mainly having difficulties to analyze whether the uses cases I write are good or not. I've read lots of theory on use cases, but the practice is being a little hard because I always find myself questioning things like: "should this be included? is this necessary to say here? isn't it missing something?" and all sorts of things like that.

So, how can I "test" my use cases? How do I know if they are well written or not? I know in OOAD iterative approach, we don't try to get it right on the first iteration, however it should at least contain the exact information to get me started in coding, and I don't now how to discover if it does contain that  information.

答:
I would have QA test them.

Seriously: if QA is able to read a use case and understand the program flow without a priori knowledge of the code (which tends to make a developer biased in terms of testing anything) then it is likely at least decent quality.

When it comes to validating requirements, use cases, and other documentation that typically comes near the start of a project you are better off involving as many stakeholders as possible in the process. If the group decides that an artifact is good quality and that each team member can get value out of it, that is quality.

For example: the customer agrees the use case accurately reflects what they want. QA agrees they can test it. Development agrees they can code it. And everyone agrees it is specific enough to remove ambiguity without unduly restricting the implementation. That is one measure of quality.


问:
Good pattern(s) for pointing to mutable state
I asked this question once here, but believe the question was unclear. However I'm having a hard time extracting the general problem from my specific case.

UPDATE: I've answered my own question below. Read on if you like reading stuff. Maybe is educational, maybe not :)

I'm writing a music sequencer. Some existing components are:

Sequence -- A collection of SequenceEvents (notes, meter, tempo, etc.)

Sequencer -- Manages playback timing

ScoreView -- Renders a sequence

NeckView -- Shows playback on guitar neck

GUI -- Manages smaller controls including clock displays of current play position

Right now, all these components are very loosely coupled, using pub/sub to send and respond to events. The exception is that the Sequencer holds a reference to a Sequence, and publishes events when the logical "playhead" moves or when sequence events are encountered. Sequence queries need to be fast during live playback, so having a single component manage such queries is important.

Some planned features require that multiple components show data related to the current playhead position, as well as a "step region", which is a time slice larger than a single time position, e.g. a measure.

The question that arises for me is how to best represent "playhead" and "step region". I don't like the idea that each component would maintain duplicate state of these time positions and associated sequence events. Even having each component maintain references to "playhead" and "step region" objects feels like a DRY violation. However simply consuming transient events doesn't work well. Consider this example:

The Sequencer advances to measure 3, beat 1, and dispatches (publishes) an event.

ScoreView handles this event, moving its playhead display.

Sequencer queries its Sequence for event data at 3:1.0, finds a 3 note chord, dispatches 3 note events.

Synth handles these events, playing the notes.

NeckView handles these events, animating the notes. So far, all works well. But...

The user edits the score, adding a 4th note at 3:1.0

Sequence dispatches a sequenceEventAdded event.

How does the NeckView know that the added note is at the "current" playhead time? Or how does it know that the added note was not at the current playhead but within the current step region, also displayed?

This is one example illustrating the problem I'm more broadly trying to solve. Having multiple components maintain their own "playhead" and "step region" data seems like redundant responsibilities and state. But doing this all with transient events starts to feel like too many event types, not a great fit either.

My best attempt to genericize this is to ask, what are good ways to represent shared mutable state? The "playhead" and "step region" both represent slices of time in a Sequence, but within those time slices, sequence events could be added/removed and observing components need to know this.

Every way I look at this feels wrong to me. Another thought is to have actual objects for a Playhead and StepRegion. Each comprises time point(s) and a subset of sequence events from the Sequence. Each could listen to the Sequence for added/removed events and re-publish these. However this approach means that multiple components now have references to a Playhead and StepRegion, which feels like a duplication of responsibilities. But if only the Sequencer holds these objects (which manages timing and logically does have a current playback position), then how do other components know to update when notes are added/removed within these time regions (as opposed to other time regions of the Sequence)?

The more I try to ask this question the dumber it sounds, but I wouldn't ask if the answer were obvious to me! Here are some multiple choice solutions:

Sequence dispatches playhead and stepRegion events. If sequence data changes for either of these time slices, it dispatches a new playhead and stepRegion event, each containing the current corresponding sequence data. Observing components like NeckView can treat these events as idempotent and remain stateless regarding timing.

Add Playhead and StepRegion classes. Multiple components can hold references to these and listen to added/removed events from these instances. This involves a fair amount of new Objects during playback, probably not a big GC concern, but smells bad.

Playhead and StepRegion are singletons. This is worse version of #2, and requires these objects maintain references to the Sequence as well as observe events from the Sequencer and re-publish events from both. Testing becomes problematic.

Sequence's added/removed events contain a reference to the Sequence object. While this seems like a sane and a common approach, it invites multiple components to do potentially expensive querying (redundantly) on the sequence as often as every tick during real-time playback. This is one reason only Sequencer directly manages a Sequence.

All observing components maintain their own time points for playhead, stepRegionStart, stepRegionEnd. Any sequenceEventAdded/Removed events can be handled or ignored accordingly. This means redundant state, but that state can completely be updated via events.

This is a long question. Any thoughts?

答:
If anyone else finds this question relevant, I'm following-up with my chosen solution. Bottom line: when you can't find a simple solution to a seemingly simple problem, it may be a sign that analysis and refactoring of the existing design is needed.

Analyzing my code, I realized that the Sequence class had fairly overloaded accessors that as designed could not be implemented without high cyclomatic complexity. By overloaded, I mean the various ways to access sequence data included a number of conditional parameters like whether to seek ahead to next available data, whether to include the start and/or end timecodes of ranges, whether to filter based on data type, etc. Also some methods were implicitly optimized for faster access. These all grew out of real use cases but the resulting complexity, even with good test coverage, made me increasingly hesitant to add to this.

I refactored into a simpler TimedCollection class that simplifies iteration and random access, with seek(timecode), peek():Timecode, next(), prev(), current() methods, which is explicitly optimized for sequential access. Sequence uses multiple TimedCollections for heterogeneous sequence data, and exposes its own iterator methods that handle returning any notes, logical tempo and meter, for every non-empty timecode. By separating iteration from the "document model", the code is much more readable, with a smaller number of methods, clearer tests, etc.

Following this refactor, I ended up doing a variation of #1 and #5 from above, having Sequencer dispatch an event for a playhead change, which consuming components can optionally retain. Sequence fires events on mutation (e.g. note added, note removed), and observing components can check against the current playhead timecode as needed. My concerns about how "correct" the solution is mostly disappeared when the underlying code became simpler and therefore easier to maintain. Put another way, when there too much complexity in the core models, there was a temptation to add more objects like "playhead" to encapsulate the inevitable percolating of that complexity through the application -- deal with edge cases and such. With simpler code a playhead doesn't require any logic and is just an anonymous object pointing to a few pieces of (immutable) data.

Kudos for reading this far. You must be bored.


问:
How to avoid errors and not miss anything
I have a problem that is more serious than it might seem.

I've been programming for about three years , and I have learned and improved a lot , I read the code easily to others, understand the problems and transform them into code, I easily adapt to new technology and I love to learn how it all works . That's all fine .

The problem I have is that I often forget small details , which then turn out to be critical . For instance , yesterday, after changing a database query to retrieve some data filtering by twenty fields , forgot to load all the data ( the query returned only the data of the primary key of the whole object ) . Other times are smaller things that do not make the whole process fails, but still I am afraid to fail at something serious , that my superiors grow weary of my mistakes , etc. .

I would like to know how I can schedule the job to not forget anything or at least soon realize that I have forgotten something or have missed something ...

答:
Code for the current set of requirements. Don't add any infrastructure for features that don't exist - they will complicate your code without delivering any immediate benefits. If you try to anticipate the future features, you'll probably be wrong anyways.

Don't optimize anything until you've measured, confirmed you have a problem, profiled, and found the bottleneck.

Avoid null like the plague. In fact, forbid it outright. It's a language flaw and a hole in the type system. Nothing good comes from using null.

Avoid mutable state. This will be a challenge outside of functional programming languages, but you should strive for it to the degree that your language will make it practical. Don't automatically slap setters on your classes if you can trivially construct a new object with the right values. Don't use a mutable data structure if a persistent version is available.

Make sure the behavior of any function or class you write is thoroughly and completely documented. (Writing small functions and classes that only do one thing will help a lot here.)

Learn how to construct a proof. It doesn't have to be extremely formal.

Get other people to review your code and proof (if any).

Unit test your code religiously in case something was overlooked. Don't bother testing every little scenario here - it's not productive. This is a sanity check; test a small handful of cases that are likely to break or are particularly tricky.

Even after doing all that, don't forget Knuth's words:

Beware of bugs in the above code; I have only proved it correct, not tried it.


答:
Programming is a bizarre activity.  Compared to any other human activity, it is devoid of any innate feedback.

I often illustrate this by comparing our work to that of a bricklayer:

To become a skilled bricklayer takes time and practice.  You need to develop a feel for the bricks, the mortar and the tools.  One thing that helps in the physical world is that the activity of laying bricks is full of feedback.

You prepare the next layer of bricks by putting up a line (a length of string aligned with the top of the new layer). Then you drop down some mortar, the amount of which you can feel when lifting it out of its bucket.  So, you can see where the next line of bricks go, and you can feel the right amount of mortar.  When you put it down, you can hear how it drops, which again confirms the amount used, and if it was placed correctly.

Next, you can pick up the next brick, and sensing its weight, you know exactly how to move it and again you use your sight and touch to decide where to drop it.  The moment it touches the mortar, you know how it drops in place.

Any deviations from the norm are automatically corrected, as you know immediately that things need to be adjusted.  You don't have to think about it, as this becomes second nature.

So how would we develop this innate feedback in programming, when that visible and tactile feedback is not present?

The closest that we've gotten so far, as far as I can see, is to introduce this feedback with Test Driven Development, and coding together.

Working together on the same code will force you to serialize your thoughts into speech, into words.  Writing failing tests first will give you confidence that you're writing sensible tests, that will help guide you towards a working solution.

Title: How to avoid errors and not miss anything

Body:
I have a problem that is more serious than it might seem.

I've been programming for about three years , and I have learned and improved a lot , I read the code easily to others, understand the problems and transform them into code, I easily adapt to new technology and I love to learn how it all works . That's all fine .

The problem I have is that I often forget small details , which then turn out to be critical . For instance , yesterday, after changing a database query to retrieve some data filtering by twenty fields , forgot to load all the data ( the query returned only the data of the primary key of the whole object ) . Other times are smaller things that do not make the whole process fails, but still I am afraid to fail at something serious , that my superiors grow weary of my mistakes , etc. .

I would like to know how I can schedule the job to not forget anything or at least soon realize that I have forgotten something or have missed something ...


答:
One method that works for me is I keep a note of everything that comes into my mind when I'm coding. I don't let them distract me and just carry on what I am coding and then I review them all at the end.

For example, I'll get half way through writing some data processing code and I'll suddenly think "I hope I disposed that file reader properly". I make a quick note and carry on with the data processing code.

Otherwise I found that was was happening was I'd think "I hope I disposed that file reader properly", go to that bit of code, check it and fix if needed and then go back to the data processing code. By then I'd lost my train of thought with that and the data processing part would be buggy.

Try to keep a note of everything you need to think about, but don't get distracted from your current coding activity or you'll introduce more bugs.


问:
Why would I want a UnitOfWork layer if my service/business logic layer is specific enough?
I'm getting into the Repository pattern (which I love), and as I read up on it I see this UnitOfWork pattern in many articles. Before I knew anything about UnitOfWork I was just using my Repository pattern inside my service layer (business logic). This seems to work great so I'm wondering why having another layer (ie. UnitOfWork) may be beneficial?

Why would I want a UnitOfWork layer in my service/business logic layer? If your service layer is specific enough and doesn't cover everything under the sun then it doesn't seem like it's needed.

Note that I'm looking at this from an EF perspective. I've even read articles where people mention that EF's DbContext is a UnitOfWork. So why make my own UnitOfWork if EF's DbContext already does this for me? Why not create my DbContext in my service layer and then pull in the repositories I need and do all good?

The Repository I get because it makes testing my services easier, but I don't see the benefit of a UnitOfWork especially if you are using an ORM.

答:
I typically use the UnitOfWork to abstract away the knowledge of database transactions (and subsequently works well as an abstraction layer over my orm). The idea is, repositories are responsible for the logic of accessessing and modifying data, the unit of work handles when those actions get performed. It's a great tool for removing some complexity and redundent database calls from your application.

Basically, the unit of work is part of your repository/data access layer, you inject a unit of work factory or provider into your repositories, who use that to perform their actions. I usually encapsulate this interaction between the unit of work and repository into a base "Repository" class.

There is an incredible amount of power and flexibility that comes from doing this. Your repositories can know less about your application, and become much more streamlined and reusable. Usually through some form of IoC container, you can set the scope of the unit of work (PerRequest) for example. Without changing any code in your repositories, you can now optimize say a web page, to do a single transaction per web request, which in some circumstances can lead to a massive performance boost in the page.

Also, by wrapping say nhibernate session in a unit of work implementation, your repositories become completely unaware of what ORM you are using, and instead focus on providing Linq queries and actions to the rest of the application. With all the transaction management taken out of your repositories, things are much cleaner, and you have a lot more flexibility when it comes to "Tuning". (Reusing your data access layer in a parsing application? Change your unit of work scope to be per file or per 1000 rows, and no code in your repositories change).

All in all, I don't really do repository pattern without a unit of work. They go hand in hand, and both are easier to do with the other one present.

OwnerDisplayName: Mitchell Lee


问:
Should I bother to write unit test for UI/UX Components?
So I am building an application with Angular and have started to get into UI testing with DalekJS (http://dalekjs.com).  As I have been writing these tests I have been thinking to myself, should I even bother with writing unit test that that are UI/UX components.

Now my angular services generally don't have anything to do with the DOM or directly rendering stuff on the page so those I unit test and it make sense however angular directives are components that render things directly to the page and writing unit tests seems like 1.  It is not an effective way to test UI/UX components and 2. It would overlap with UI/UX Tests.

For point #1, unit test (at least ones I have seen) don't actually write anything to a browser and render it.  For thing that require DOM, you generally mock the DOM in a variable and use that to test whatever you need to test.  If you have an error with a test, you can't load it up in a browser and play around with it like you could with UI/UX tests (which in my experience runs against code that is the true application that renders and everything).

For point #2, one of my directives has a property called contentVisible.  Now I can write a unit test that make sure that property is the correct value at certain points but that really don't not test what I truly want to test because even if contentVisible is set to false, the content still might be rendering to the screen which UI/UX test would pick up.

Is it still worth the effort to write unit test for UI/UX Components where UI tests would be able to pick up everything the unit test would plus also do a better job since it can test what is actually rendered?

Exception
The one exception case where I would need a unit test is for certain ajax requests.  For example, making sure an ajax request is not made of that an ajax request that does not make and changes to the UI are things that can only be tested with unit tests.

答:
My fuzzy answer is that sometimes having UI unit tests is a good idea, for some parts of the UI. In my experience:

Often the people responsible for functional and integration testing are different people than those responsible for unit testing (typically, QA vs. Dev). As such, each may spot different areas (and have different blind spots) as to what ought to be covered by tests.

Related to this, programmers should be responsible for testing their own code, and not defer some aspects simply because someone else is theoretically testing that code.

Unit tests are more targeted than full functional tests. While the latter might tell you that an expected button is not clickable, it won't instantly tell you that this is because it's enabled property is false vs. it's z-index is wrong vs. its layout coordinates are outside the viewport, etc. Likewise, as you point out, the unit test can tell you that the visible property is set correctly, but  does not necessarily tell you if the object is actually visible (though such tests are possible). In other words, even with trivial examples you can see that the two types of tests are not interchangeable.

Belt and suspenders approaches are often fine [for software engineers].

Trying to test any aspect of code -- GUI, time-based, async -- will tend to improve one's thinking about that code and its design. The trade-off is that too many tests or testing the wrong level of abstraction can slow refactoring. But imho it's high-value to try to test any part and learn from experience what types of tests add the most value.

I've worked on a couple of large projects where having the programmers unit test a lot of parts of the UI saved a LOT of time and made the QA folks happier (and able to focus more on things programmers could not have spotted as easily). I should add, I do not like testing UI code because it's time-consuming and hard. In general writing tests is time-consuming but pays for itself rapidly, and good UI unit tests that add specificity to what functional tools can test are no exception.


答:
Your service layer might look simple now, but if you are building this application for a client they ultimately shape the service layer, not you.

What if the client requires that they can edit multiple items at once, changing any number of item properties, some of which are part of denormalized database tables? What happens when EF throws a concurrency exception during one of these commits?

Things can get real messy real fast. Just because a pattern exists doesn't mean you need to find a place to apply it in your application. One answer to your question is that you might want an additional UoW layer when you need to implement your own change tracking and concurrency handling logic beyond what EF provides as part of the DbContext.

Title: Why would I want a UnitOfWork layer if my service/business logic layer is specific enough?

Body:
I'm getting into the Repository pattern (which I love), and as I read up on it I see this UnitOfWork pattern in many articles. Before I knew anything about UnitOfWork I was just using my Repository pattern inside my service layer (business logic). This seems to work great so I'm wondering why having another layer (ie. UnitOfWork) may be beneficial?

Why would I want a UnitOfWork layer in my service/business logic layer? If your service layer is specific enough and doesn't cover everything under the sun then it doesn't seem like it's needed.

Note that I'm looking at this from an EF perspective. I've even read articles where people mention that EF's DbContext is a UnitOfWork. So why make my own UnitOfWork if EF's DbContext already does this for me? Why not create my DbContext in my service layer and then pull in the repositories I need and do all good?

The Repository I get because it makes testing my services easier, but I don't see the benefit of a UnitOfWork especially if you are using an ORM.


问:
Is there something a `Promise` can do that `async` cannot?
Recently, I've spent a lot of time trying to dive into, and understand, Javascript Promises, especially those adhering to the Promises/A+ spec. What I'm trying to understand is whether or not Promises actually give developers additional tools specifically when compared to CPS based async, or whether it is mostly syntactic sugar and a tool to reduce verbosity or streamline some behaviors.

One argument I've heard for promises is error handling. In that case, using the async library it is very easy to execute a async.waterfall of functions, each waiting for the prior to complete, each wrapped in a try/catch to handle synchronous errors (since neither Promises, nor async handle async errors), passing caught errors to an error handler. In that situation Promises and async behave identically regarding error semantics (gist showing this behavior).

Another argument I've heard for promises is future-proofing methods which are sync now, but asynchronous later on. The theory is that if the function returns a promise, it doesn't matter what if it is modified later. Since both sender and receiver have to modified to adhere to the promise contract, can't the same argument be stated for modifying both sender and receiver to use the CPS contract, even if it's synchronous, to future proof it?

So with that in mind is there any use-case that you can think of which can only be solved optimally by Promises or is their usage really more a case of preference and the desire to reduce verbosity and reduce the chance of error?

答:
I believe the two main benefits of Promises are:

Much more readable code that describes the sequence of operations clearly. I think of "sugar" as saving typing or obscuring (often magic) complexity, whereas in this case, what's more salient is providing greatly increased clarity and therefore more solid, less error-prone code. As Knuth said, code is primarily for humans, and incidentally is executable by computers.

Ability to ignore whether an operation has already completed or not at the time the calling code executes. This is different than future-proofing, which is about being agnostic at the time of writing the code. Some Promise implementations allow returning promise objects that have already resolved but can still have then() called. Sometimes this nicely deals with otherwise race conditions.

I'm not deeply experienced with them, but I don't believe there are any significant advantages other than the above. But, the above are very big advantages.

The one disadvantage I've run into is using different libraries whose Promise implementations had subtle differences, like the behavior of calling then() on an already resolved promise. Also the problem that where library A (ngluar, *cough*) could accept promise objects in many places, but was using explicit rather than duck typing, you'd get into annoying situations where you have to wrap library B's promise's with library A's promises, having the opposite effect of sugar. This is basically a side effect of Javascript having neither native Promises nor any mechanism for a standard library, but it is a real world caveat.

Also the terminology is slightly silly. Thenable?


答:
From: http://martinfowler.com/eaaCatalog/repository.html

Repository also supports the objective of achieving a clean separation
  and one-way dependency between the domain and data mapping layers.

The issue is here:

So why make my own UnitOfWork if EF's DbContext already does this for me?

If you are using a classic repository pattern, the service layer would not know that there is a DbContext, or a db at all, the service layer just knows of a repository, and that calling the repository gets the data from parts unknown and returns it.

if the service layer is unaware of the storage mechanism, how would it perform a transaction? how would it perform transaction-like interactions across different providers (different databases, web services, etc...)? The UnitOfWork pattern is more general than a database transaction and helps to coordinate the Repositories in a transactional manner, spanning databases, potentially even spanning client requests.


问:
Is there any performance benefit in checking the item count prior to executing a foreach loop?
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?

答:
Looking at the source code of System.Collections.Generic.List<T> we see that MoveNext() is implemented like this:

```<code>public bool MoveNext() {
    List<T> localList = list;

    if (version == localList._version && ((uint)index < (uint)localList._size))
    {
        current = localList._items[index];
        index++;
        return true;
    }
    return MoveNextRare();
}
</code>```

Meaning that the total cost of one check is

Assigning an existing collection to another variable

Comparing versions, whatever that is

Casting two int values to uint and comparing them

When we look at the source code of .Count:

```<code>public int Count {
    get {
        lock (_root) {
            return _list.Count;
        }
    }
}
</code>```

We see that the cost is acquiring a lock.

Conclusion

You can go measure and see which one performs best but I think it's safe to conclude that none of this will ever matter. You might have some uncommon collections to iterate over that don't do an early size check, but that's a very specific edge case that will point itself out then.

Bottom line: don't worry about it and you shouldn't bother adding a .Count > 0 or _collection != null check in the first place.

Body:
Looking at the source code of System.Collections.Generic.List<T> we see that MoveNext() is implemented like this:

public bool MoveNext() {
    List<T> localList = list;

    if (version == localList._version && ((uint)index < (uint)localList._size))
    {
        current = localList._items[index];
        index++;
        return true;
    }
    return MoveNextRare();
}

Meaning that the total cost of one check is

Assigning an existing collection to another variable

Comparing versions, whatever that is

Casting two int values to uint and comparing them

When we look at the source code of .Count:

public int Count {
    get {
        lock (_root) {
            return _list.Count;
        }
    }
}

We see that the cost is acquiring a lock.

Conclusion

You can go measure and see which one performs best but I think it's safe to conclude that none of this will ever matter. You might have some uncommon collections to iterate over that don't do an early size check, but that's a very specific edge case that will point itself out then.

Bottom line: don't worry about it and you shouldn't bother adding a .Count > 0 or _collection != null check in the first place.


问:
What kind of processes or static alaysis would you use to catch impropper buffer bugs such as the one that caused heartbleed?
What kind of process or static analysis would catch the heart bleed bug other than human code reviews which we already know failed. The Fix Commit is here. </p>

答:
One common solution is to use managed languages. Languages like Java have bounds checking and memory clearing on assignment that would prevent the issue. The Java VM has been getting very fast after years and years of work and sometimes even beats C code nowadays, so the performance hit isn't as great as you would expect. And high performance isn't required for all coding projects anyway.

Another common solution being discussed is to not reimplement core library functions in your own code. The built-in malloc on Linux and other modern systems has config options to clear the memory to prevent sensitive things from being accessed for example, as well as guard pages to help prevent reading too far. OpenSSL has their own memory allocation, however, so wasn't able to take advantage of common C support and tools to mitigate issues:
http://www.tedunangst.com/flak/post/heartbleed-vs-mallocconf

Using core functions would have helped analysis tools like Valgrind catch the problem as well.


答:
Ultimately, the best answer is to actually test it.  Make a method which loops over an empty array with and without checking the length first, call each 100,000 times and see which has a faster runtime.

```<code>public void withCheck(Integer[] array) {
    for (int i = 0; i < 100000; i++) {
        if (array.length > 0) {
            for (Integer i : array) {
                // nothing to do.
            }
        }
    }
}

public void withoutCheck(Integer[] array) {
    for (int i = 0; i < 100000; i++) {
        for (Integer i : array) {
            // nothing to do.
        }
    }
}

public void test() {
    long startTime = System.currentTimeMillis();
    withCheck();
    System.out.println("Time with check: " + (System.currentTimeMillis() - startTime) + "ms");
    startTime = System.currentTimeMillis();
    withoutCheck();
    System.out.println("Time without check: " + (System.currentTimeMillis() - startTime) + "ms");
}
</code>```

When I write code like this, I generally ponder this as a trade-off between code readability and perceived or potential performance.  In other words, adding a if (count > 0) check negatively impacts the readability, even though by a very small amount.  So what is the gain?  I presume there is very little or no advantage, but like you, I have not actually tested it.  What I can tell you is that in all my years profiling, I have never found looping over an empty array to be a bottleneck.

Technically, it depends on how the iterator works.  For a foreach loop like you have, you are creating an iterator object behind the scenes.  My expectation would be, and again, this is unverified, is that the iterator object FOR AN ARRAY would simply be implemented like this (this is Java, but C# is probably comparable):

```<code>public class ArrayIterator<T> implements Iterator<T> {
    private int next = 0;
    public T next() {
        return backingArray[next++];
    }

    public boolean hasNext() {
        return next < backingArray.length;
    }
}
</code>```

So iterating over such an iterator should exit out very quickly because hasNext() will return false.  Notice it's the same check that your if statement would do.

Now if you are iterating over a linked list, the implementation should be different.  If you explicitly check the size, you may be forcing it to scan the linked list.  In Java, LinkedList.size() checks an explicit size variable so it doesn't walk the list, but I don't know how .NET implements it.

Another way to look at this is how likely is the collection to be empty?  If that is a rare case, then if the theory that iterating over an empty array takes time is true, then adding an explicit check for empty first would only be faster if the collection is usually empty.  If not, you are theoretically slowing down your average case just to slightly speed up your worst case.

Again, these are all theories and the timings are on the micro-level, so take it with a grain of salt.

TL;DR

It depends on the type of collection, the runtime platform, and the typical collection size, but intuitively, it seems unlikely to speed anything up in most situations.  But the only way to know for sure is to test it.

Title: Is there any performance benefit in checking the item count prior to executing a foreach loop?

Body:
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?

Body:
Ultimately, the best answer is to actually test it.  Make a method which loops over an empty array with and without checking the length first, call each 100,000 times and see which has a faster runtime.

public void withCheck(Integer[] array) {
    for (int i = 0; i < 100000; i++) {
        if (array.length > 0) {
            for (Integer i : array) {
                // nothing to do.
            }
        }
    }
}

public void withoutCheck(Integer[] array) {
    for (int i = 0; i < 100000; i++) {
        for (Integer i : array) {
            // nothing to do.
        }
    }
}

public void test() {
    long startTime = System.currentTimeMillis();
    withCheck();
    System.out.println("Time with check: " + (System.currentTimeMillis() - startTime) + "ms");
    startTime = System.currentTimeMillis();
    withoutCheck();
    System.out.println("Time without check: " + (System.currentTimeMillis() - startTime) + "ms");
}

When I write code like this, I generally ponder this as a trade-off between code readability and perceived or potential performance.  In other words, adding a if (count > 0) check negatively impacts the readability, even though by a very small amount.  So what is the gain?  I presume there is very little or no advantage, but like you, I have not actually tested it.  What I can tell you is that in all my years profiling, I have never found looping over an empty array to be a bottleneck.

Technically, it depends on how the iterator works.  For a foreach loop like you have, you are creating an iterator object behind the scenes.  My expectation would be, and again, this is unverified, is that the iterator object FOR AN ARRAY would simply be implemented like this (this is Java, but C# is probably comparable):

public class ArrayIterator<T> implements Iterator<T> {
    private int next = 0;
    public T next() {
        return backingArray[next++];
    }

    public boolean hasNext() {
        return next < backingArray.length;
    }
}

So iterating over such an iterator should exit out very quickly because hasNext() will return false.  Notice it's the same check that your if statement would do.

Now if you are iterating over a linked list, the implementation should be different.  If you explicitly check the size, you may be forcing it to scan the linked list.  In Java, LinkedList.size() checks an explicit size variable so it doesn't walk the list, but I don't know how .NET implements it.

Another way to look at this is how likely is the collection to be empty?  If that is a rare case, then if the theory that iterating over an empty array takes time is true, then adding an explicit check for empty first would only be faster if the collection is usually empty.  If not, you are theoretically slowing down your average case just to slightly speed up your worst case.

Again, these are all theories and the timings are on the micro-level, so take it with a grain of salt.

TL;DR

It depends on the type of collection, the runtime platform, and the typical collection size, but intuitively, it seems unlikely to speed anything up in most situations.  But the only way to know for sure is to test it.


问:
Creating nested functions for purely aesthetic reasons?
I've always wondered what other programmers think about the idea of creating pure aesthetic functions.

Say I have a function that processes a chunk of data: Function ProcessBigData. Say I need several process steps, only valid for that data: Step1, Step2, Step3.

The normal aproach I see the most in source code is to write comments like so:

```<code>Function ProcessBigData:
    # Does Step1
    Step1..
    Step1..

    #Does Step2
    Step2..
    Step2..
</code>```

What I usually do, but always felt wrong due to the lack of such coding style by fellow peers is:

```<code>Function ProcessBigData:
    Function Step1:
        Step1..
        Step1..

    Function Step2:
        Step2..
        Step2..

    Step1() -> Step2()
</code>```

I am mainly concerned if there any drawbacks for such style in Javascript and Python

Are there any alternatives that I'm not seeing?

答:
It's not as strange as you might think. For example, in Standard ML it's customary to limit the scope of helper functions. Granted, SML has syntax to facilitate it:

```<code>local
    fun recursion_helper (iteration_variable, accumulator) =
        ... (* implementation goes here *)
in
    fun recursive_function (arg) = recursion_helper(arg, 0);
end
</code>```

I would consider this good style, given that 1) small functions facilitate reasoning about the program, and 2) it signals to the reader that these functions are not used outside of that scope.

I suppose it's possible there's some overhead in creating the inner functions whenever the outer function is called (I don't know if JS or Python optimize that away) but you know what they say about premature optimization.

Body:
It's not as strange as you might think. For example, in Standard ML it's customary to limit the scope of helper functions. Granted, SML has syntax to facilitate it:

local
    fun recursion_helper (iteration_variable, accumulator) =
        ... (* implementation goes here *)
in
    fun recursive_function (arg) = recursion_helper(arg, 0);
end

I would consider this good style, given that 1) small functions facilitate reasoning about the program, and 2) it signals to the reader that these functions are not used outside of that scope.

I suppose it's possible there's some overhead in creating the inner functions whenever the outer function is called (I don't know if JS or Python optimize that away) but you know what they say about premature optimization.


问:
Which do you code first, MVC?
I have been coding for a good bit, and I found a project I want to work on -- a python web app using django + mongodb.

I know what I want my web app to do. When you are in this circumstance (just starting a brand new project) where do you start? What do you code first? Do you code the views first?

Hope this hasn't been asked before (I did a quick look), but I could use some general direction.

答:
It is best to start with your model.  Your controllers will be based on your model, and then you make the views to access the controllers.

UI/View logic should always be the last thing you work on, as it can change as the data changes, but if you design your model first, you are working using a bottom-up approach, so by the time you reach your view, you'll have everything established and know how your views are supposed to access the data.

Ideally, you'll be doing test cases on each step, so that when you reach your view, you know exactly how your going to be persisting and retrieving your data.

Title: Which do you code first, MVC?


答:
It is usually a good thing to do this whenever possible, but I like to think of this sort of work not as "steps", but as subtasks.

A subtask is a specific unit of work that can be done: it has a specific responsibility, and defined input(s) and output(s) (think of the "S" in SOLID). A subtask need not be re-usable: some people tend to think "I'll never have to call this from anything else so why write it as a function?" but that's a fallacy.

I'll try to also outline the benefits and also how it applies to nested functions (closures) vs just another function in the class. Generally speaking, I'd recommend not using closures unless you specifically need one (there are many uses, but separating code into logical chunks is not one of them).

Readability.

200+ lines of procedural code (body of a function) are hard to read. 2-20 line functions are easy to read. Code is for humans.

Nested or not, you mostly get the benefit of readability, unless you're using a lot of variables from the parent scope, in which case it can be just as difficult to read.

Limit variable scope

Having another function forces you to limit variable scope, and specifically pass what you need.

This often also makes you structure code better, because if you need some sort of state variable from an earlier "step", you might actually find there's actually another subtask that should written and executed first to get that value. Or in other words, it makes it harder to write highly-coupled chunks of code.

Having nested functions allows you to access variables in the parent scope from inside the nested function (closure). This can be very useful, but it can also lead to subtle, hard-to-find bugs since the execution of the function may not happen in the way it's written. This is even more the case if you're modifying variables in the parent scope (a very bad idea, generally).

Unit tests

Each subtask, implemented a function (or even a class) is a stand-alone, testable piece of code. The benefits of unit testing and TDD are well documented elsewhere.

Using nested functions/closures doesn't allow unit testing. To me, this is a deal-breaker and the reason that you should just another function, unless there is a specific need for a closure.

Working on a team / Top-down design

Subtasks can be written by different people, independently, if needed.

Even by yourself, it can be useful when writing code to simply invoke some subtask that doesn't yet exist, while building the main functionality, and worry about actually implementing the subtask only after you know it's going to get the results you need in a meaningful way. This is also called Top-down design/programming.

Code re-use

Okay, so despite what I said earlier, sometimes there actually does end up being a reason later to re-use a subtask for something else. I'm not at all advocating "architecture astronaut"-ism but just that by writing loosely-coupled code, you may end up benefiting later from re-use.

Often that re-use means some refactoring, which is perfectly expected, but refactoring the input parameters to a small standalone function is MUCH easier than extracting it from a 200+ line function months after it was written, which is really my point here.

If you use a nested function, re-using it is generally a matter of refactoring to a separate function anyway, which again, is why I'd argue that nested is not the way to go.

Title: Creating nested functions for purely aesthetic reasons?

Body:
I've always wondered what other programmers think about the idea of creating pure aesthetic functions.

Say I have a function that processes a chunk of data: Function ProcessBigData. Say I need several process steps, only valid for that data: Step1, Step2, Step3.

The normal aproach I see the most in source code is to write comments like so:

```<code>Function ProcessBigData:
    # Does Step1
    Step1..
    Step1..

    #Does Step2
    Step2..
    Step2..
</code>```

What I usually do, but always felt wrong due to the lack of such coding style by fellow peers is:

```<code>Function ProcessBigData:
    Function Step1:
        Step1..
        Step1..

    Function Step2:
        Step2..
        Step2..

    Step1() -> Step2()
</code>```

I am mainly concerned if there any drawbacks for such style in Javascript and Python

Are there any alternatives that I'm not seeing?


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
I regularly surf the web from my smart phone's web browser when I'm not at home or the office. While it supports (at least a subset of) JavaScript it doesn't always handle it well. I've found many websites unusable because they either consume to many resources or just crash the browser.

I prefer the built-in browser, but I keep two alternate browsers around in case one of them does a better job.

ContentLicense: CC BY-SA 2.5


答:
Some of the advantages of promises are that they make asynchronous operations a "first-class" entity. They can be transformed, they are composable, and their use also happens to reduce nesting and make handling of async code more analogous to sync code. To me, it is usually more readable to have a chain of promises than nested callbacks. Many modern languages have moved to promise-style async.

See: http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/

Title: Is there something a `Promise` can do that `async` cannot?

Body:
Recently, I've spent a lot of time trying to dive into, and understand, Javascript Promises, especially those adhering to the Promises/A+ spec. What I'm trying to understand is whether or not Promises actually give developers additional tools specifically when compared to CPS based async, or whether it is mostly syntactic sugar and a tool to reduce verbosity or streamline some behaviors.

One argument I've heard for promises is error handling. In that case, using the async library it is very easy to execute a async.waterfall of functions, each waiting for the prior to complete, each wrapped in a try/catch to handle synchronous errors (since neither Promises, nor async handle async errors), passing caught errors to an error handler. In that situation Promises and async behave identically regarding error semantics (gist showing this behavior).

Another argument I've heard for promises is future-proofing methods which are sync now, but asynchronous later on. The theory is that if the function returns a promise, it doesn't matter what if it is modified later. Since both sender and receiver have to modified to adhere to the promise contract, can't the same argument be stated for modifying both sender and receiver to use the CPS contract, even if it's synchronous, to future proof it?

So with that in mind is there any use-case that you can think of which can only be solved optimally by Promises or is their usage really more a case of preference and the desire to reduce verbosity and reduce the chance of error?


问:
Are (C) object files created with different compilers binary-compatible?
I understand that C++ compilers are not compatible with each other. However, I was unable to find anything on this topic for C in particular. I know that the C standard leaves a lot of room for compilers to implement things however they see fit: for example, the size and alignment of most (all?) data types is implementation-defined save for some minimal guarantees. Therefore, two compilers (or two versions of the same compiler) can disagree on numerous details.

Am I correct in thinking that there's no guarantee that two object files compiled with different compilers will actually link properly? For example, the size of pointers could be 32 bits in one object file and 64 bits in the other. But if that's so, why are C libraries sometimes distributed in precompiled form? Is there an expectation that I'll use the same compiler they did (e.g. gcc), or some de facto standard being used to ensure binary compatibility? And how do other languages with a Foreign Language Interface ensure things will line up properly when linking with C object files?

答:
What you are looking for in called an ABI (Application Binary Interface).

The C language does not define an ABI, so in that sense there is indeed no guarantee that C files compiled with different compilers will work with each other.

On the other hand, on most platforms the OS defines an ABI for interfacing with it and all compilers targeting that OS & processor family also use that same ABI for interfacing with non-OS components. So, in practice, C objects created by different compilers can work with each other.


问:
Why we should (not) develop on a server via RDP
I have a client who is requesting that we develop their fairly small web application directly in their environment by RDP to the server that will host the app. They have had a contractor do this for a while and it has worked "fine" for them, so they are comfortable with that approach. The client's biggest concern at this point is cutting costs - they have a very tight budget.

My manager does not seem to care or think that it makes a difference. However, I strongly do not agree with that practice.

How best can I convince the client that it is bad practice to do things that way? I need to use "management" language, not developer language.

I can think of a few advantages of developing locally (as a developer):

We can not guarantee code quality in the remote environment (why not?)

Internal team collaboration increases efficiency (how?)

Internally, we can take better advantage of source control (although that can also be installed on the server)

Internally, we can follow better quality control processes

With RDP, only one developer can work on project at a time

Developing locally increases a developer's efficiency (how? maybe because it is their comfort zone? maybe with multiple monitors? how does that benefit the client?)

Unfortunately, these do not necessarily translate to something management appreciates (e.g. dollars and cents)

Please help.

答:
You're trying to use a bulldozer to hoe a garden.  Stop it.

The client & your management are happy with the current (primitive, simple, dangerous) process.

This process works for a small app with a single trusted developer.

Since you're making all your changes on production, if you introduce a bug it's likely that someone will spot it quickly.  Not all businesses consider a bug to be catastrophic - they just expect you to fix it.  They also get instant feedback on the work you're doing.

This sort of customer is relatively unsophisticated and may not appreciate the value that testing, source control, team collaboration, QA, backups etc can bring.

Until the customer's ready to advance, any attempt to bring in "all that overhead" will be met with resistance.

(From a technical point of view you are of course absolutely correct.  From a business point of view, all that mumbo-jumbo techie stuff sounds complicated and doesn't visibly add to the bottom line)


问:
Why isn't there an html tag "field"?
There is a <fieldset> tag for a set of fields.

Why isn't there a hierarchical child for fieldsets?

```<code><form>
    <fieldset>
        <legend>Thin Sandwich Options</legend>
        <field>
            <label>Meat</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="meat" value="turkey" />Turkey</label>
                <label>
                    <input type="radio" name="meat" value="monkey" />Monkey</label>
            </div>
            <div class='desc'>Pick one meat for the thin sandwich.</div>
        </field>
        <field>
            <label>Cheese</label>
            <div class='inputs'>
                <label>
                    <input type="checkbox" name="cheese" value="chedder" />Cheddar</label>
                <label>
                    <input type="checkbox" name="cheese" value="swiss" />Swiss</label>
            </div>
            <div class='desc'>Pick one meat for the thin sandwich.</div>
        </field>
    </fieldset>
    <fieldset>
        <legend>Beverage Options</legend>
        <field>
            <label for="carbonated">Carbonated</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="carbonated" value="coke" />Coke</label>
                <label>
                    <input type="radio" name="carbonated" value="mtn-dew" />Dew</label>
            </div>
            <div class='desc'>Pick one beverage per combo.</div>
        </field>
        <field>
            <label for="non-carbonated">Non Carbonated</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="non-carbonated" value="tea-sweet" />Tea (non sweetend)</label>
                <label>
                    <input type="radio" name="non-carbonated" value="tea" />Tea</label>
            </div>
        </field>
    </fieldset>
</form>
</code>```

http://jsfiddle.net/5dC8c/

I keep coming back to this question whenever I am working on my HTML form layouts.

As MDN defines it:

The HTML <fieldset> element is used to group several controls as
  well as labels () within a web form.

I see a <field> element as grouping a single control (or set of radio buttons) with a single label and a description. The field tag would have some of the same attributes that the input tag has, readonly, required, etc.

Why does bootstrap use the class 'form-group'?

Why does Wufoo use li tags for each field?

Enclosing related form elements into fields would add clarity.

Every major front-end framework has some class or tag to differentiate each field.

Why the heck don't we have a single HTML tag to bring some normality to form design?

Update: added a better HTML example of the usage of a <field> tag.

答:
It's an optional element to allow for grouping of form elements.

The form elements, such as input, exist outside of the fieldset, do wrapping them inside field tags when inside a fieldset is redundant.

Title: Why isn't there an html tag "field"?


答:
The short answer is: because <field> would be redundant (or worse).

What would a "field" be in this context?  Well, I would expect it to mean any form-associated element in  the field set that potentially delivers input.

But the there is no need to designate these as "fields" because ... well ... we / the browser already know they are fields.  Wrapping them in a <field> element achieves almost nothing1. From the perspective of someone reading / writing the HTML <field> would just be syntactic noise.

1 - I can see a small benefit for javascript (etc) code.  A <field> element would make it simpler for javascript to query the DOM to find all designated fields in a fieldset ... or a form.  But the flipside is that if <field> has a special meaning (e.g. to Javascript programs), then forgetting a <field> tag is a potential source of errors.

Title: Why isn't there an html tag "field"?

Body:
There is a <fieldset> tag for a set of fields.

Why isn't there a hierarchical child for fieldsets?

```<code><form>
    <fieldset>
        <legend>Thin Sandwich Options</legend>
        <field>
            <label>Meat</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="meat" value="turkey" />Turkey</label>
                <label>
                    <input type="radio" name="meat" value="monkey" />Monkey</label>
            </div>
            <div class='desc'>Pick one meat for the thin sandwich.</div>
        </field>
        <field>
            <label>Cheese</label>
            <div class='inputs'>
                <label>
                    <input type="checkbox" name="cheese" value="chedder" />Cheddar</label>
                <label>
                    <input type="checkbox" name="cheese" value="swiss" />Swiss</label>
            </div>
            <div class='desc'>Pick one meat for the thin sandwich.</div>
        </field>
    </fieldset>
    <fieldset>
        <legend>Beverage Options</legend>
        <field>
            <label for="carbonated">Carbonated</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="carbonated" value="coke" />Coke</label>
                <label>
                    <input type="radio" name="carbonated" value="mtn-dew" />Dew</label>
            </div>
            <div class='desc'>Pick one beverage per combo.</div>
        </field>
        <field>
            <label for="non-carbonated">Non Carbonated</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="non-carbonated" value="tea-sweet" />Tea (non sweetend)</label>
                <label>
                    <input type="radio" name="non-carbonated" value="tea" />Tea</label>
            </div>
        </field>
    </fieldset>
</form>
</code>```

http://jsfiddle.net/5dC8c/

I keep coming back to this question whenever I am working on my HTML form layouts.

As MDN defines it:

The HTML <fieldset> element is used to group several controls as
  well as labels () within a web form.

I see a <field> element as grouping a single control (or set of radio buttons) with a single label and a description. The field tag would have some of the same attributes that the input tag has, readonly, required, etc.

Why does bootstrap use the class 'form-group'?

Why does Wufoo use li tags for each field?

Enclosing related form elements into fields would add clarity.

Every major front-end framework has some class or tag to differentiate each field.

Why the heck don't we have a single HTML tag to bring some normality to form design?

Update: added a better HTML example of the usage of a <field> tag.


问:
How to do an effective code review of library changes?
One of my projects just changed the version number of a supporting third-party library. Specifically, we changed a J2EE app from JPA 1.x to JPA 2.0. Our CI system has had this change for a week and the tests are passing.

In general, how can I do an effective code review and QA check when another developer changes the version of a third-party library?

I have already  done the following:

reviewed the changelogs for the library, watching for things that would affect my application

checked the dependency declarations (Maven POMs) for mistakes

searched our ticketing system for prior attempts or upgrades of the same libraries, did we try this before and fail or find a blocker

答:
If the library follows the Open/closed principle, then you just need to review the release notes for any significant changes.  If not, there should be a migration guide to help you upgrade.  The release notes usually list significant new features as well as any deprecated features.  Plan your strategy on dealing with the deprecated features.  You may also want to plan modifications to take advantage of new features.

On occasion, I have seen libraries which try to follow the Open/closed principle violate it to add new functionality.  This has been documented with a discussion on the reasons why they broke the principle, and notes on how to adapt.

Review the changelog for changes significant to your project.  If you depend on or have worked around a bug in the library's behavior, review the changelog to see if the bug has been addressed.  Review the changelog for subsequent releases to see if they identify any bugs that apply to your project.

You may want to review Javadoc, if available, of both versions to see if there are any significant changes.  You may want to limit the comparison to the features you use.  Any differences should already have been addressed by the items above.

Run you test suites against the new code.  Don't panic if you get failures.  These may be newly correct behavior.  Assess each failure, and determine how to proceed.

Review any code changes implemented in the change that implemented the new library.  These should only be the changes, if any, required to change version.  The prior steps should have identified the types of changes you see.


问:
What conclusion to be drawn from no difference in generated assembly from 2 rather different programs?
I might not have had a counterexample when I got the reply "A pointer is just an address, what's the difficulty?" but I didn't really buy such a simple explanation and at assembly code it's not obvious what's a pointer for 2 different C programs that generate the same assembly.

```<code> cat pelle.s valle.s
    .file   "pelle.c"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    movl    $0, %eax
    popl    %ebp
    .cfi_def_cfa 4, 4
    .cfi_restore 5
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
    .section    .note.GNU-stack,"",@progbits
    .file   "valle.c"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    movl    $0, %eax
    popl    %ebp
    .cfi_def_cfa 4, 4
    .cfi_restore 5
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
    .section    .note.GNU-stack,"",@progbits
</code>```

1) An address to a variable is &var1 and the pointer is int* var1 written differently than the address. 2) When I compile 2 C programs where the only difference is pointing then there is no difference in the assembly:

```<code>$ diff pelle.c valle.c ;cat pelle.c valle.c;diff pelle.s valle.s
3c3
< int * pelle;
---
>  int valle;
#include <stdio.h>
int main(void) {
int * pelle;
    return 0;
}
#include <stdio.h>
int main(void) {
 int valle;
    return 0;
}
1c1
<   .file   "pelle.c"
---
>   .file   "valle.c"
</code>```

But what conclusions can be drawn from no difference in generated assembly to investigate the "simple and obvious difference" between a pointer declaration and other type? Is the simplistic answer right all along, a pointer is just a variable and there's no point in more analysis? Or that the difference between a pointer and a variable is a case of "sugar" since the types are removed at assembly level where there is no difference? Will a difference in the generated assembly show a diff if I use pointers as arguments to a function and there will indeed be a difference for some pointer usage and this example is too trivial and can't be generalized? So when types are removed in the generated assembly, can I conclude that type difference indeed will result in a difference i nthe generated assembly for a non-trivial example e.g. pointers as arguments and this example is not very good since it looks like the generated assembly disregards typing, while type difference such as this will make a difference in generated assembly for another example?

```<code>int valle;
int * pelle;

 Assembler

.data
.align 2
.global valle
valle: .word 0

.data
.align 2
.global pelle
pelle: .word 0
</code>```

答:
The only absolute conclusion you can draw is that the two programs will behave the same if they have been compiled with the same compiler for the same target platform.

If you then analyse the differences in the source code, you may also be able to deduce that there are semantic similarities / equivalences.

In fact, it is highly likely that there will be semantic equivalences at the source code level ... though they may depend on non-portable assumptions in the code; e.g. that an int and an int* have the same size.


答:
An RDP connection is going to be slower to work on due to the latency. You'll type a line of code, and have to wait a bit for it to show up. On a fast connection (LAN) this probably won't be noticeable, but on a slow connection (like over an ADSL link) this will be noticeable, and (in my experience):

Make you work much slower (as you wait for the keyboard and the mouse pointer to catch up). If you're billing by the hour this might be something that your client will have an issue with.

Drive you slowly insane (after an hour of working over RDP I gave up and just drove to the other office).

Title: Why we should (not) develop on a server via RDP

Body:
I have a client who is requesting that we develop their fairly small web application directly in their environment by RDP to the server that will host the app. They have had a contractor do this for a while and it has worked "fine" for them, so they are comfortable with that approach. The client's biggest concern at this point is cutting costs - they have a very tight budget.

My manager does not seem to care or think that it makes a difference. However, I strongly do not agree with that practice.

How best can I convince the client that it is bad practice to do things that way? I need to use "management" language, not developer language.

I can think of a few advantages of developing locally (as a developer):

We can not guarantee code quality in the remote environment (why not?)

Internal team collaboration increases efficiency (how?)

Internally, we can take better advantage of source control (although that can also be installed on the server)

Internally, we can follow better quality control processes

With RDP, only one developer can work on project at a time

Developing locally increases a developer's efficiency (how? maybe because it is their comfort zone? maybe with multiple monitors? how does that benefit the client?)

Unfortunately, these do not necessarily translate to something management appreciates (e.g. dollars and cents)

Please help.


答:
You've come up with the answer you want and now you're just soliciting confirmation. STOP IT.

The correct question isn't "Why shouldn't we...." -- rather it's "Should we...." Research the underlying question, don't just try to support the answer you want.

Here's some starters:

PRO

Lower cost (multiple thin clients)

Higher flexibility (any machine will do as long as it supports RDP)

Single predictable environment for building and development

Greater control over the code; it all stays in one place

Code can't "get lost" on someone's laptop somewhere; management always knows where the latest version is

Easy to transfer ownership of the project between programmers; just give them the new VM

and much more. I'm not event trying...

CON

Only one copy = single point of failure

Greater opportunity for trade-secret exfiltration by a malicious developer

Requires an always-on Internet connection

Development environment is maddening over a high-latency link

RDP sometimes "gets in the way" -- keystrokes get interpreted by the host OS, for example


答:
There is, it's called <input>.

The <input> tag came first. But then came the desire to group inputs (and typically the radio button variety in particular) into visually-distinct groups. Names like <inputgroup> or <inputset> just wouldn't fly. But <fieldset>  sounds pretty good, so that's the name they used.

<input> wasn't renamed to <field> for consistency because that would break all sorts of stuff. And honestly is that sort of consistency really necessary? This is HTML, after all.

FWIW, <legend> was introduced at the same time to complete the visual experience. Combining the two allowed you to draw a box with a label around the form like this:

It's like Windows 95 all over again. This was a level of UI sophistication previously only available in such fine development environments as Visual Basic 5.0. Bringing that sort of design capability to HTML was a big deal.

Title: Why isn't there an html tag "field"?


答:
If the two programs generate the same assembly, then you can be certain that if assembled using the same assembler, those will produce the same machine code. And that's about it.

But if that were the only point, then we'd all be coding in assembly. Programming languages are about abstractions. That's literally the whole point.

In C, pointers are part of that abstraction, but there's more than one way to achieve the same result. The result you achieve isn't how you measure the value of the abstraction, rather it's the baseline upon which the abstraction is constructed.

What matters is how a given language feature makes the code easier to reason through, easier to avoid mistakes, easier to communicate to others. And if that's not your goal, then you might as well write your code in assembly.

Title: What conclusion to be drawn from no difference in generated assembly from 2 rather different programs?

Body:
I might not have had a counterexample when I got the reply "A pointer is just an address, what's the difficulty?" but I didn't really buy such a simple explanation and at assembly code it's not obvious what's a pointer for 2 different C programs that generate the same assembly.

```<code> cat pelle.s valle.s
    .file   "pelle.c"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    movl    $0, %eax
    popl    %ebp
    .cfi_def_cfa 4, 4
    .cfi_restore 5
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
    .section    .note.GNU-stack,"",@progbits
    .file   "valle.c"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    movl    $0, %eax
    popl    %ebp
    .cfi_def_cfa 4, 4
    .cfi_restore 5
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
    .section    .note.GNU-stack,"",@progbits
</code>```

1) An address to a variable is &var1 and the pointer is int* var1 written differently than the address. 2) When I compile 2 C programs where the only difference is pointing then there is no difference in the assembly:

```<code>$ diff pelle.c valle.c ;cat pelle.c valle.c;diff pelle.s valle.s
3c3
< int * pelle;
---
>  int valle;
#include <stdio.h>
int main(void) {
int * pelle;
    return 0;
}
#include <stdio.h>
int main(void) {
 int valle;
    return 0;
}
1c1
<   .file   "pelle.c"
---
>   .file   "valle.c"
</code>```

But what conclusions can be drawn from no difference in generated assembly to investigate the "simple and obvious difference" between a pointer declaration and other type? Is the simplistic answer right all along, a pointer is just a variable and there's no point in more analysis? Or that the difference between a pointer and a variable is a case of "sugar" since the types are removed at assembly level where there is no difference? Will a difference in the generated assembly show a diff if I use pointers as arguments to a function and there will indeed be a difference for some pointer usage and this example is too trivial and can't be generalized? So when types are removed in the generated assembly, can I conclude that type difference indeed will result in a difference i nthe generated assembly for a non-trivial example e.g. pointers as arguments and this example is not very good since it looks like the generated assembly disregards typing, while type difference such as this will make a difference in generated assembly for another example?

```<code>int valle;
int * pelle;

 Assembler

.data
.align 2
.global valle
valle: .word 0

.data
.align 2
.global pelle
pelle: .word 0
</code>```


问:
Simple Design for Singleton function in java for Kernel
I understand that Singelton helps to instantiate only one class AT A TIME. I try to learn how to Design for Singleton function in java.  I want to know it better to understand Kernel. So I try to do this following, but I like to know if it's the only way to come up with private constructor.</p>

```<code>public class Singleton {
    private static Singleton instance = null;

    private Singleton() {   }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
                    instance = new Singleton ();
        }
        return instance;
    }
}
</code>```

答:
yes, to create a Singleton class, you have to use the private constructor as it is the only way to prevent another class from creating an instance of your class.  </p>

```<code>public class Singleton {
private static Singleton instance = null;

private Singleton() {   }

public static synchronized Singleton getInstance() {
    if (instance == null) {
                instance = new Singleton ();
    }
    return instance;
}
</code>```

<p>}</p>

Body:
yes, to create a Singleton class, you have to use the private constructor as it is the only way to prevent another class from creating an instance of your class.

public class Singleton {
private static Singleton instance = null;

private Singleton() {   }

public static synchronized Singleton getInstance() {
    if (instance == null) {
                instance = new Singleton ();
    }
    return instance;
}

}


答:
The fact that two programs compile to the same assembly code means that the two programs produce the same behavior.
Differences in programs that don't contribute to the behavior (such as the unused variables in your examples) may or may not show up in the assembly code. The compiler is fully within its rights to throw those parts out completely.

Assembly languages are untyped, which means that the concept of types doesn't exist in assembly.
The concept of a type is a higher-level concept that limits what you can do with a variable.

In assembly language, a variable is nothing more than a piece of memory or a register that has been set aside for a particular purpose (where that purpose is determined by the programmer). The assembler will allow you to perform any known operation on a variable and it is your responsibility to ensure that the operation makes sense.

In higher-level languages that have the concept of types, you inform the compiler how you intend to use a variable ("I intend to use valle as a location for numbers and pelle as a location for addresses of integer variables") and the compiler takes on part of the burden to ensure that the operations you do with a variable make sense.

When compiling a higher-level language, the compiler checks that the type rules are obeyed by the program, but it throws the type information away after that because there is no way to keep it in assembly or machine language.

When reading assembly, the only way to derive type information is to look at how variables are being used in the generated assembly. And even then, the inferred type information may be incomplete.


问:
What's the difference between model for test and model for development?
What's the difference between model for test and model for development?

Is it that the model for test contains only what we should test? Do we use the same diagrams in model for test and model for development?

For example, if we use sequence diagrams for generating test cases, these diagrams will not be used for coding?

I speak in the context of Model Based Testing (MBT).

答:
Ideally there should not be a difference. That is, different parts of model might be elaborated in more detail for test, others might be elaborated in more detail for development.

However, the scenario in which the test team goes off to make its own sequence diagram which is ignored by the development team is problematic to say the least. A recipe for frustration on both sides.

Of course, you may encounter a scenario in which the development team has not bought into the idea of model-driven development. In this case, making the sequence diagrams from the paper specification and asking the development team (who in this case has most likely developed little or no documentation of their own) to review them with you may be helpful.

However, the ultimate goal of model-driven development (or all sorts of systems - not just software) is to get all the stakeholders (test, electrical, mechanical, software, accounting, legal, etc...) to buy into the "model"  as the "single version of the truth".


答:
The practice of "outside-in" test-driven development recommends coding the UI first, driven by tests in which you stub out the back end. You continue working down the layers of your application like this, testing (and coding) each layer of the onion until you are ready to move inwards; the model is typically the last thing you write.

This has advantages and disadvantages. Having a working UI prototype you can show customers means you can iterate the design of your UI quickly without getting bogged down in the data model. It also helps you keep your UI decoupled from the model, and it feels encouraging to have a visible working UI early on in the development process.

On the other hand, the UI is typically much harder to test than the model. It requires discipline to remember to test your model code at a lower level, and not rely on fragile acceptance tests for all your testing.

I'd recommend a balanced approach, switching between outside-in and inside-out styles as is appropriate for the situation at hand.

Title: Which do you code first, MVC?

Body:
I have been coding for a good bit, and I found a project I want to work on -- a python web app using django + mongodb.

I know what I want my web app to do. When you are in this circumstance (just starting a brand new project) where do you start? What do you code first? Do you code the views first?

Hope this hasn't been asked before (I did a quick look), but I could use some general direction.


答:
They produce the same assembly because the compiler removes the unused variable. It does not contribute to the code, so it does not show up in the assembly. You may be able to see a difference if you turn off all optimizations.

But let's look at the assembly after removing all cruft (added line numbers for making the explanation simpler):

```<code>1: main:
2:    pushl   %ebp
3:    movl    %esp, %ebp
4:    movl    $0, %eax
5:    popl    %ebp
6:    ret
</code>```

What this essentially does is to set up the stack frame for a new function (line 2 and 3), set the return value to 0 (line 4) and restore the stack frame and return from the function (lines 5 and 6).

This translates to the following C code:

```<code>int main(void)
{
    return 0;
}
</code>```

Which is exactly what the compiler sees after removing the variable that is not being used.

So in short, the conclusion is that the assembly is the same because the programs are the same. The fact that you declare a local variable that does not contribute to the program does not make it a different program.

Body:
They produce the same assembly because the compiler removes the unused variable. It does not contribute to the code, so it does not show up in the assembly. You may be able to see a difference if you turn off all optimizations.

But let's look at the assembly after removing all cruft (added line numbers for making the explanation simpler):

1: main:
2:    pushl   %ebp
3:    movl    %esp, %ebp
4:    movl    $0, %eax
5:    popl    %ebp
6:    ret

What this essentially does is to set up the stack frame for a new function (line 2 and 3), set the return value to 0 (line 4) and restore the stack frame and return from the function (lines 5 and 6).

This translates to the following C code:

int main(void)
{
    return 0;
}

Which is exactly what the compiler sees after removing the variable that is not being used.

So in short, the conclusion is that the assembly is the same because the programs are the same. The fact that you declare a local variable that does not contribute to the program does not make it a different program.


问:
A specific problem with architecturing a part of our application
Firstly, I'll try to describe the real world model of what we are trying to express in C# code.

We have a device called M100. It's purpose is to read\write data from\into cards (plastic or ULTRALIGHT cards such as MIFARE). It can be with one up to 3 antennas (the device read\write data through antenna). One of antennas is internal (so card can be put on the device surface and the device will be able to perform read\write operations), the other are external. Let's consider the usual situation. We have a point of service terminal. M100 reside inside the terminal and it has two external antennas wich are placed over a tract of cards dispenser. Cards dispenser is another device which is responsible for accepting and dispensing cards for performing read\write operations by M100. So, card dispenser takes the card from the user, move it to the read\write position and after that M100 can perform read\write operations. M100 can be equipped with only one (internal) antenna. So we have to main cases: with and without card dispensers.

We have one application that interacts with dispensers and the other uses M100 without card dispensers.

We developed M100Provider with it's interface IM100Provider. This is the low-level class which interacts with M100 directly, passes commands through COM-port.

We have a higher level-operations such as AuthorizeOperator, WriteTicket, ReadCard (all this operations require M100) so we developed M100Communicator class (maybe the name does not reflect it's intention at the time, but we will think about the name a bit later). M100Communicator is a singleton. Because we need to manipulate card dispensers to accept and dispense users cards M100Communicator interacts with CardDispensersManager class. We haven't decide yet wil it be composed into M100Communicator or will it be a singleton (it seems like it's a singleton).

All these operations are have to perform in a kind of a unified way:

Block the current object.

Check if there are some dispensers configured

If they are - pass to them a command to open the tract for card acception.

Pass to M100 a command to search a card through specified antennas.

When the card was found, perform read\write operations.

Dispense card back to the user.

Here are the problems we are faced:

Considering that M100Communicator sometimes doesn't require CardDispensersManager we are forced to check it's state to null reference everywhere (and it will be quite strange to have a special case CardDispensersManager which will  return meaningfull responses while there are no dispensers!).

M100Communicator and CardDispensersManager have to be initialized from the start of the system so it's unclear how to update the configuration of CardDispensersManager and M100Communicator and how to communicate with CardDispensersManager directly when we want to close ports and stop communication with dispensers explicitly, because it will be very strange to expose dispensers API through M100Communicator. (yes we have the requirement to be able to access dispensers API from everywhere, so we think that CardsDispenserManager has to be a singleton).

答:
Your problem is exactly same kind of problem this exercise on software design describes.

Instead of designing the code around specific device, you should design abstraction that describes process of reading a card. Then, this abstraction can be concretized to specific devices. If you design you software this way, the problems you are facing will be solved during creation of the concrete objects for specific application.