Is there any recommended way to return property values through getters? - php-extension

I'm playing a bit with writing php extensions and trying to figure out what would be the best way to return class private property value through method (registered by the extension of course).
Here is what I have so far:
PHP_MINIT_FUNCTION(uamqp_connection) {
// class initialization
zend_declare_property_bool(this_ce, "boolValue", sizeof("boolValue") - 1, 0, ZEND_ACC_PRIVATE);
}
And then method:
PHP_METHOD(Test, getBool)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_BOOL(zval_get_long(zend_read_property(this_ce, getThis(), "boolValue", sizeof("boolValue") -1, 1, NULL)));
}
I'm not sure about this zval_get_long passed later to RETURN_BOOL, is that something that could be considered valid way? Is there any easier/more obvious solution? This one seems to work but I still dont feel confident about it.

Related

Return an item by id

I got this piece of code, I am learning from tutorial. I want to return an element by url which looks like clients/1 instead of clients?id=1. How can I achieve this? Also, can the code below be made easier way?
#GetMapping
public Client getClient(#RequestParam int id) {
Optional<Client> first = clientList.stream().filter(element -> element.getId() == id).findFirst();
return first.get();
}
You may want to use #PathVariable as follows:
#Controller
#RequestMapping("/clients")
public class MyController {
#GetMapping("/{id}")
public Client getClient(#PathVariable int id) {
return clientList.stream().filter(element -> element.getId() == id).findFirst().orElseThrow();
}
Please note, the Optional can be unpacked with orElseThrow method. This will throw a NoSuchElementException in case there is no element found for the id.
Other solution would be to use orElse(new Client(...)) to return a default value if nothing is found.
get() is not really recommended to be used. From the JavaDoc of the get() method:
API Note:
The preferred alternative to this method is orElseThrow().
Even though get() may also throw a NoSuchElementException, similar to orElseThrow, usually the consensus is that get should not be used without isPresent, or should not be used at all. There several other methods to unpack the Optional without forcing you write an if.
The whole idea of the Optional is to overcome this by forcing you to think about the case when there is no value inside.

How do I call a javascript function from Go/WASM using Invoke that acts upon a js.Value?

I need to check for fullscreen support with my Go WASM Canvas project, before switching to fullscreen mode. I have the following code so far:
var fullscreenFunc js.Value
var fullscreenNotSupported bool
set with the following logic:
fullscreenFunc = app.Get("requestFullscreen")
if fullscreenFunc.IsUndefined() {
fullscreenFunc = app.Get("mozRequestFullScreen")
if fullscreenFunc.IsUndefined() {
fullscreenFunc = app.Get("webkitRequestFullscreen")
if fullscreenFunc.IsUndefined() {
fullscreenFunc = app.Get("msRequestFullscreen")
if fullscreenFunc.IsUndefined() {
fullscreenNotSupported = true
println("Fullscreen not supported")
}
}
}
}
I was expecting to be able to call the correct function with js.Invoke, but I see no way to tell the Invoke upon which object the call should be made. My 'app' value is being interpreted just as a param.
func Fullscreen(app js.Value) {
if fullscreenNotSupported {
return
}
fullscreenFunc.Invoke(app)
}
resulting in:
panic: JavaScript error: 'mozRequestFullScreen' called on an object that does not implement interface Element.
So am I correct in my thinking that the only way I can call the correct method, is not to store the Function, but to store a string of the function name, and then 'invoke' / 'call' it using the following approach?
app.Call(fullscreenFunctionNameString)
It feels like I misunderstood the purpose of Invoke. Is it only for js.Global() type calls?
[edit] Using 'Call', at least it seems possible to derive the function name without having to repeat the above browser specifics:
fullscreenFunctionName = fullscreenFunc.Get("name").String()
app.Call(fullscreenFunctionNameString)
It doesn't answer the question, but is probably of help to someone trying to do the same.
The arguments to invoke get turned into arguments for the javascript function it wraps. Since those fullscreen functions don't need any arguments, I think you might just need to change:
fullscreenFunc.Invoke(app)
To:
fullscreenFunc.Invoke()
...assuming app is the same JS element in both places. If not your Call solution is probably your best bet.

Is it good practice for void methods to return?

The return statement is being used in void methods to break out of the logic here. The problem is the consumers of the method wouldn’t know whether the logic in the method ran completely or not, when we do this. However my architect and teams don't agree with that. The reason is that the current consumer in this case doesn't care about the outcome.
I think this is coding anti-pattern. It is like eating exception with out bubbling it up. What's everyone's opinion on this?
Existing code:
Private void XXX(final String parameter) {
try {
if (parameter==null){
return;
}
....
}
My version
Private boolean XXX(final String parameter) {
try {
if (parameter==null){
return false;
}
....
return true;
}
In general having multiple returns is not necessarily an anti-pattern. At worst there might be many exit points in the method which can be confusing for developers who are reading the code and perhaps make it harder to maintain...maybe but that is not what you seem to be asking.
The code samples you provided appear to me to both be anti-patterns.
The problem is the consumers of the method wouldn’t know whether the logic in the method ran completely or not, when we do this.
First, that is what Exceptions are for. If there is a problem while executing the code in the method, throw an Exception with an intent revealing type and a good message describing the problem.
The first version of your code:
Private void XXX(final String parameter) {
try {
if (parameter==null){
return;
}
....
}
seemed to return instead of throwing an Exception with an invalid argument.
The second version of the code:
Private boolean XXX(final String parameter) {
try {
if (parameter==null){
return false;
}
....
return true;
}
Seems to return a boolean as an exit code of "worked" or "didn't work". This isn't very helpful because if it didn't work, you don't know why. Also it requires the calling code to check the return value which they might forget to do.
There's nothing wrong with having an explicit return for a void method. However, it is good general practice--if possible--to have just one return from a method (although you can have more than one if logic demands it and you write the code as simply as possible--no blocks--so that the overall flow is not obfuscated).
Should you simply return in the case you cite? It all depends on the requirements. Your customers appear to be the programmers who will call this method. Do they consider a null parameter to be a logic error for the method or do they consider it to be valid?
If it's the former then I suggest you use an annotation (#NotNull) to ensure that parameter is not null. Unfortunately, there are several of these to choose from so you will have to figure out which suits your architecture best.
If you really don't want to use an annotation (and null is considered an error) then throw an exception.

Getting DataContext error while saving form

I get this error when opening one specific form. The rest is working fine and I have no clue why this one isn't.
Error: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
I get the error at _oDBConnection when I try to save. When I watch _oDBConnection while running through the code, it does not exist. Even when I open the main-window it does not exist. So this form is where the DataContext is built for the very first time.
Every class inherits from clsBase where the DataContext is built.
My collegue is the professional one who built it all. I am just expanding and using it (learned it by doing it). But now I'm stuck and he is on holiday. So keep it simple :-)
What can it be?
clsPermanency
namespace Reservation
{
class clsPermanency : clsBase
{
private tblPermanency _oPermanency;
public tblPermanency PermanencyData
{
get { return _oPermanency; }
set { _oPermanency = value; }
}
public clsPermanency()
: base()
{
_oPermanency = new tblPermanency();
}
public clsPermanency(int iID)
: this()
{
_oPermanency = (from oPermanencyData in _oDBConnection.tblPermanencies
where oPermanencyData.ID == iID
select oPermanencyData).First();
if (_oPermanency == null)
throw new Exception("Permanentie niet gevonden");
}
public void save()
{
if (_oPermanency.ID == 0)
{
_oDBConnection.tblPermanencies.InsertOnSubmit(_oPermanency);
}
_oDBConnection.SubmitChanges();
}
}
}
clsBase
public class clsBase
{
protected DBReservationDataContext _oDBConnection;
protected int _iID;
public int ID
{
get { return _iID; }
}
public DBReservationDataContext DBConnection
{
get { return _oDBConnection; }
}
public clsBase()
{
_oDBConnection = new DBReservationDataContext();
}
}
Not a direct answer, but this is really bad design, sorry.
Issues:
One context instance per class instance. Pretty incredible. How are you going to manage units of work and transactions? And what about memory consumption and performance?
Indirection: every entity instance (prefixed o) is wrapped in a cls class. What a hassle to make classes cooperate, if necessary, or to access their properties.
DRY: far from it. Does each clsBase derivative have the same methods as clsPermanency?
Constructors: you always have to call the base constructor. The constructor with int iID always causes a redundant new object to be created, which will certainly be a noticeable performance hit when dealing with larger numbers. A minor change in constructor logic may cause the sequence of constructor invocations to change. (Nested and inherited constructors are always tricky).
Exception handling: you need a try-catch everywhere where classes are created. (BTW: First() will throw its own exception if the record is not there).
Finally, not a real issue, but class and variable name prefixes are sooo 19xx.
What to do?
I don't think you can change your colleague's design in his absence. But I'd really talk to him about it in due time. Just study some linq-to-sql examples out there to pick up some regular patterns.
The exception indicates that somewhere between fetching the _oPermanency instance (in the Id-d constructor) and saving it a new _oDBConnection is created. The code as shown does not reveal how this could happen, but I assume there is more code than this. When you debug and check GetHashCode() of _oDBConnection instances you should be able to find where it happens.

How to take advantage of an auto-property when refactoring this .Net 1.1 sample?

I see a lot of legacy .Net 1.1-style code at work like in example below, which I would like to shrink with the help of an auto-property. This will help many classes shrink by 30-40%, which I think would be good.
public int MyIntThingy
{
get
{
return _myIntThingy;
}
set
{
_myIntThingy = value;
}
} private int _myIntThingy = -1;
This would become:
public int MyIntThingy
{
get;
set;
}
And the only question is - where do I set MyIntThingy = -1;?
If I wrote the class from the start, then I would have a better idea, but I did not. An obvious answer would be: put it in the constructor. Trouble is: there are many constructors in this class. Watching the initialization to -1 in the debugger, I see it happen (I believe) before the constructor gets called. It is almost as if I need to use a static constructor as described here:
http://www.c-sharpcorner.com/uploadfile/cupadhyay/staticconstructors11092005061428am/staticconstructors.aspx
except that my variables are not static. Java's static initializer comes to mind, but again - my variables are not static. http://www.glenmccl.com/tip_003.htm
I want to make stylistic but not functional changes to this class. As crappy as it is, it has been tested and working for a few years now. breaking the functionality would be bad. So ... I am looking for shorter, sweeter, cuter, and yet EQUIVALENT code. Let me know if you have questions.
I'm afraid that you have no option.
If you want to use an auto-property with an initial value that differs from the type's default value then you'll need to set the initial value in the constructor(s).
If you just need a stylistic, non-breaking change, consider changing the format a little:
public int MyIntThingy
{
get { return _myIntThingy; }
set { _myIntThingy = value; }
}
private int _myIntThingy = -1;
Isn't that prettier?
And consider using auto-properties for future code only. It sounds too risky to use them on existing code, unless there are no default values.

Resources