Error "Method InventMovement.pdsCWRemainPhysical must be overridden" - dynamics-ax-2012-r3

Retail\Journals\Open statements
while calculating statement in the Retail error is prompting.
"Method InventMovement.pdsCWRemainPhysical must be overridden."
Statements form error
I placed breakpoint and i found a checkmark for CatchWt item InventMovement.pdsCWRemainPhysical()
method should be overridden for Catch wt items.
checkmark in script
Does it mean for Catch wt items there is limitation in Retail module.?
we can't able to post a statement for catch weight items in default application(need to do customization)?

Take a look at method updateEstimate of table RetailTransactionSalesTrans (from the stack trace of your second screenshot). There the InventMovement object is created. If you take a look at the construct method of class InventMovement you will see that for retail statements, an instance of class InventMov_Statement is created. This is a subclass of InventMovement which does not overwrite the pdsCWRemainPhysical method, which in turn causes the error you describe.
I'm not familiar enough with the catch weight functionality to answer your question if catch weight items are allowed in the retail module. But at least for the statement calculation there is a gap (and in my view a bug in the standard application).
A customization should be easy, just overwrite method pdsCWRemainPhysical (and probably other pdsCW* methods) in class InventMov_Statement. Of course you first have to define what values these methods should return for retail statements. To do that you might want to compare how these methods are implemented in other subclasses of InventMovement (e.g. InventMov_Sales). Please make sure to test such a customization for possible side effects.

Related

Exception handling: does more statements in a try block lead to fallible code?

In many languages exception handling uses two or more blocks of code, try and one or more catch's.
Exception handling in V language (v0.2.4), although different syntax only allows a single statement in try. One of the developers motivation is that the language won't allow try blocks because that is "error prone".
I can't see any arguments that supports this so my question is: does allowing more statements in a try block lead to fallible code?
I see a quite big drawback with only one statement in a try: you may end up with more code duplication in cases where you need to attach exact same error handler. This can be alleviated to some degree by moving code to a error handling function, in some cases this is an unnecessary function declaration that you'd need to call multiple times following another and it looks quite stupid.
On a side note, one benefit with only one statement is that you don't need to declare the variable outside, this can be useful in some cases.

Design Patterns for dependent sequential validation

I have three validators each sequentially dependent on the previous. I might use all three or only the first two or only the first one. E.g.
Validator 1: Checks whether user exists
Validator 2: Checks whether requested order exists in the user's order history
Validator 3: Checks whether that order has a cancel option
Each validator in this list will throw an error if the previous condition is not met. I'm currently using this pattern:
function validator1() { ... }
function validator2() { validator1(); ... }
function validator3() { validator2(); ... }
But this feels like an anti-pattern to me because all of the prerequisite validation is done implicitly so when I run validtor2(), it is not clear that validator1() is also being run.
I also considered doing this:
function validator1() { ... }
function validator2() { ... }
function validator3() { ... }
function someTask() { validator1(); validator2(); validator3(); ... }
But this is unsafe because there is nothing stopping me from running validator3() and throwing an error if condition 2 hasn't been met.
Is there a way to do this that is both safe and explicit?
Edit
This is a great reference for the design pattern mentioned in the accepted answer: https://refactoring.guru/design-patterns/chain-of-responsibility
I suggest looking into the Chain of Responsibility and the Builder Pattern specific for validation.
See here:
https://medium.com/#aleksanderkolata/java-tips-01-handle-validation-in-an-elegant-manner-using-chain-of-responsibility-design-pattern-ad3dcc22479e
https://medium.com/henrydchan/input-validation-using-design-patterns-9d7b96f87702
You could also look into usage of the Decorator Pattern:
https://www.google.com/amp/s/robdodson.me/javascript-design-patterns-decorator/amp/
Is there a way to do this that is both safe and explicit?
But before considering one of the patterns which might of course provide more flexibility but also more complexity consider if your rules might really get extended a lot and will be reused and that many cases. Otherwise it might be a bit of over engineering to go with one of the suggested patterns right away.
Also, you can make a lot explizit by using meaningful function names that explicitly tell the reader of the code what specific use case is being performed. Such a function than acts more like an orchestrator of the required validation steps. So your approach (despite of the bad name someTask()) might already fit your needs.
But this is unsafe because there is nothing stopping me from running validator3() and throwing an error if condition 2 hasn't been met.
You could either have each validate exception throw an exception or introduce guard clauses having the major task return if one of the validations fail.
Another option would be to pass in or register a list of validations with the same interface and loop them through. If you need to check for all validations and collect the results (e.g. error code or messages) for each validation step or throw an exception on the first validation is up to your needs.

Why use an exception instead of if...else

For example, in the case of "The array index out of bound" exception, why don't we check the array length in advance:
if(array.length < countNum)
{
//logic
}
else
{
//replace using exception
}
My question is, why choose to use an exception? and when to use an exception, instead of if-else
Thanks.
It depends on acceptable practices for a given language.
In Java, the convention is to always check conditions whenever possible and not to use exceptions for flow control. But, for example, in Python not only using exception in this manner is acceptable, but it is also a preferred practice.
They are used to inform the code that calls your code an exceptional condition occurred. Exceptions are more expensive than well formed if/else logic so you use them in exceptional circumstances such as reaching a condition in your code you cannot handle locally, or to support giving the caller of your code the choice of how to handle the error condition.
Usually if you find yourself throwing and catching exceptions in your own function or method, you can probably find a more efficient way of doing it.
There are many answers to that question. As a single example, from Java, when you are using multiple threads, sometimes you need to interrupt a thread, and the thread will see this when an InterruptedException is thrown.
Other times, you will be using an API that throws certain exceptions. You won't be able to avoid it. If the API throws, for example, an IOException, then you can catch it, or let it bubble up.
Here's an example where it would actually be better to use an exception instead of a conditional.
Say you had a list of 10,000 strings. Now, you only want those items which are integers. Now, you know that a very small number of them won't be integers (in string form). So should you check to see if every string is an integer before trying to convert them? Or should you just try to convert them and throw and catch an exception if you get one that isn't an integer? The second way is more efficient, but if they were mostly non-integers then it would be more efficient to use an if-statement.
Most of the time, however, you should not use exceptions if you can replace them with a conditional.
As someone has already said, 'Exceptions' in programming languages are for exceptional cases and not to set logical flow of your program. For example, in the case of given code snippet of your question, you have to see what the enclosing method's or function's intention is. Is checking array.length < countNum part of the business logic or not. If yes, then putting a pair of if/else there is the way to go. If that condition is not part of the business logic and the enclosing method's intention is something else, then write code for that something else and throw exception instead of going the if/else way. For example you develop an application for a school and in your application you have a method GetClassTopperGrades which is responsible for the business logic part which requires to return the highest marks of the student in a certain class. the method/function definition would be something like this:
int GetClassTopperGrades(string classID)
In this case the method's intention is to return the grades, for a valid class, which will always be a positive integer, according to the business logic of the application. Now if someone calls your method and passes a garbage string or null, what should it do? If should throw an exception e.g. ArgumentException or 'ArgumentNullException' because this was an exceptional case in this particular context. The method assumed that always a valid class ID will be passed and NULL or empty string is NOT a valid class ID (a deviation from the business logic).
Apart from that, in some conditions there is no prior knowledge about the outcome of a given code and no defined way to prevent an exceptional situation. For example, querying some remote database, if the network goes down, you don't have any other option there apart from throwing an exception. Would you check network connectivity before issuing every SQL query to the remote database?
There is strong and indisputable reason why to use exceptions - no matter of language. I strongly believe that decision about if to use exceptions or not have nothing to do with particular language used.
Using exceptions is universal method to notify other part of code that something wrong happened in kind of loosely coupled way. Let imagine that if you would like to handle some exceptional condition by using if.. nad else.. you need to insert into different part of your code some arbitrary variables and other stuff which probably would easily led to have spaghetti code soon after.
Let next imagine that you are using any external library/package and it's author decided to put in his/her code other arbitrary way to handle wrong states - it would force you to adjust to its way of dealing with it - for example you would need to check if particular methods returns true or false or whatever. Using exceptions makes handling errors much more easy - you just assume that if something goes wrong - the other code will throw exception, so you just wrap the code in try block and handle possible exception on your own way.

Naming conventions for methods which must be called in a specific order?

I have a class that requires some of its methods to be called in a specific order. If these methods are called out of order then the object will stop working correctly. There are a few asserts in the methods to ensure that the object is in a valid state. What naming conventions could I use to communicate to the next person to read the code that these methods need to be called in a specific order?
It would be possible to turn this into one huge method, but huge methods are a great way to create problems. (There are a 2 methods than can trigger this sequence so 1 huge method would also result in duplication.)
It would be possible to write comments that explain that the methods need to be called in order but comments are less useful then clearly named methods.
Any suggestions?
Is it possible to refactor so (at least some of) the state from the first function is passed as a paramter to the second function, then it's impossible to avoid?
Otherwise, if you have comments and asserts, you're doing quite well.
However, "It would be possible to turn this into one huge method" makes it sound like the outside code doesn't need to access the intermediate state in any way. If so, why not just make one public method, which calls several private methods successively? Something like:
FroblicateWeazel() {
// Need to be in this order:
FroblicateWeazel_Init();
FroblicateWeazel_PerformCals();
FroblicateWeazel_OutputCalcs();
FroblicateWeazel_Cleanup();
}
That's not perfect, but if the order is centralised to that one function, it's fairly easy to see what order they should come in.
Message digest and encryption/decryption routines often have an _init() method to set things up, an _update() to add new data, and a _final() to return final results and tear things back down again.

What are the cons of returning an Exception instance instead of raising it in Python?

I have been doing some work with python-couchdb and desktopcouch. In one of the patches I submitted I wrapped the db.update function from couchdb. For anyone that is not familiar with python-couchdb the function is the following:
def update(self, documents, **options):
"""Perform a bulk update or insertion of the given documents using a
single HTTP request.
>>> server = Server('http://localhost:5984/')
>>> db = server.create('python-tests')
>>> for doc in db.update([
... Document(type='Person', name='John Doe'),
... Document(type='Person', name='Mary Jane'),
... Document(type='City', name='Gotham City')
... ]):
... print repr(doc) #doctest: +ELLIPSIS
(True, '...', '...')
(True, '...', '...')
(True, '...', '...')
>>> del server['python-tests']
The return value of this method is a list containing a tuple for every
element in the `documents` sequence. Each tuple is of the form
``(success, docid, rev_or_exc)``, where ``success`` is a boolean
indicating whether the update succeeded, ``docid`` is the ID of the
document, and ``rev_or_exc`` is either the new document revision, or
an exception instance (e.g. `ResourceConflict`) if the update failed.
If an object in the documents list is not a dictionary, this method
looks for an ``items()`` method that can be used to convert the object
to a dictionary. Effectively this means you can also use this method
with `schema.Document` objects.
:param documents: a sequence of dictionaries or `Document` objects, or
objects providing a ``items()`` method that can be
used to convert them to a dictionary
:return: an iterable over the resulting documents
:rtype: ``list``
:since: version 0.2
"""
As you can see, this function does not raise the exceptions that have been raised by the couchdb server but it rather returns them in a tuple with the id of the document that we wanted to update.
One of the reviewers went to #python on irc to ask about the matter. In #python they recommended to use sentinel values rather than exceptions. As you can imaging just an approach is not practical since there are lots of possible exceptions that can be received. My questions is, what are the cons of using Exceptions over sentinel values besides that using exceptions is uglier?
I think it is ok to return the exceptions in this case, because some parts of the update function may succeed and some may fail. When you raise the exception, the API user has no control over what succeeded already.
Raising an Exception is a notification that something that was expected to work did not work. It breaks the program flow, and should only be done if whatever is going on now is flawed in a way that the program doesn't know how to handle.
But sometimes you want to raise a little error flag without breaking program flow. You can do this by returning special values, and these values can very well be exceptions.
Python does this internally in one case. When you compare two values like foo < bar, the actual call is foo.__lt__(bar). If this method raises an exception, program flow will be broken, as expected. But if it returns NotImplemented, Python will then try bar.__ge__(foo) instead. So in this case returning the exception rather than raising it is used to flag that it didn't work, but in an expected way.
It's really the difference between an expected error and an unexpected one, IMO.
exceptions intended to be raised. It helps with debugging, handling causes of the errors and it's clear and well-established practise of other developers.
I think looking at the interface of the programme, it's not clear what am I supposed to do with returned exception. raise it? from outside of the chain that actually caused it? it seems a bit convoluted.
I'd suggest, returning docid, new_rev_doc tuple on success and propagating/raising exception as it is. Your approach duplicates success and type of 3rd returned value too.
Exceptions cause the normal program flow to break; then exceptions go up the call stack until they're intercept, or they may reach the top if they aren't. Hence they're employed to mark a really special condition that should be handled by the caller. Raising an exception is useful since the program won't continue if a necessary condition has not been met.
In languages that don't support exceptions (like C) you're often forced to check return values of functions to verify everything went on correctly; otherwise the program may misbehave.
By the way the update() is a bit different:
it takes multiple arguments; some may fail, some may succeed, hence it needs a way to communicate results for each arg.
a previous failure has no relation with operations coming next, e.g. it is not a permanent error
In that situation raising an exception would NOT be usueful in an API. On the other hand, if the connection to the db drops while executing the query, then an exception is the way to go (since it's a permament error and would impact all operations coming next).
By the way if your business logic requires all operations to complete successfully and you don't know what to do when an update fails (i.e. your design says it should never happen), feel free to raise an exception in your own code.