How function call can implement between SWC's in AUTOSAR - function

I want a particular function to be executed and return a value to another SWC in AUTOSAR architecture. for example :
SWC-1
boolean operation(int a, int b)
{
if (a == b)
return true;
else
return false;
}
SWC - 2
int main()
{
int a = 2, b = 3;
boolean ret = false;
ret = operation(2,3);
if(ret == true)
{
//perform some activity
}
}
I want to a perform operation function call in SWC-2. The function is defined in SWC-1. In AUTOSAR architecture, how can i configure these functions? Can i do it as sender receiver method or client- server method ? Which is the best way to design in AUTOSAR ?

This is obviously a case for client/server communication. The function operation has to be modeled as a ClientServerOperation inside a ClientServerInterface. Also, an RPortPrototype (typed by the ClientServerInterface) is required to exist on SWC2 for calling the operation using the Rte_Call API for calling the operation.
The server side is a bit more complicated to configure and it would take some effort to explain everything in detail. I‘d recommend having a look at the AUTOSAR specification documents „TPS Software Component Template“ and „SWS RTE“ to understand how the interaction between the software-components works.

Related

How to make a reference of or call a member function if that member function exists

I want to check that if a member function of a particular name exists on a object, if it does call the member function or make a reference of that member function.
Here I don't have type of the object, i.e. the object maybe does not implement any interface but has a member function cancel().
I used this method (reflection) to check if the member function exists, i.e. if (object::class.members.any { it.name == "cancel" }) and when this statement returns true I am sure that the method does exist but compiler is still unsure that the 'cancel' method exist in the object or not
fun canceller(object: Any): KFunction<Any>?
{
var canceller: KFunction<Any>? = null
// check if object has member function 'cancel'
if (object::class.members.any { it.name == "cancel" })
{
// make reference of that member function and return it
canceller = object::cancel //cancel is still not recognized as a member function and gives an error that "Unresolved reference: cancel"
// or just call it now
// object.cancel()
}
return canceller
}
I expect that canceller variable should be assigned to value.cancel(), but the compiler is unsure that cancel() function exist (with an error "Unresolved reference: cancel") in the object even after we supplied a check inside if statement
It's not meant to be used like this. Reflection is something you use if you don't know at compile time what you are dealing with at runtime. Some examples:
you need to use a type that's configured in some properties file (Class.forName("someTypeString").newInstance())
you have written an utility that extracts the contents of your object for debugging purposes
you need to access code that isn't really visible to you (private fields that you can't easily access, but you need to)
many more... but most of the time very special use-cases
Now what you have shown is a function reference (object::cancel). In order to use a function reference the compiler must know the type of object and the cancel-function must exist for that type. As object is of type Any and the if-condition is only relevant at runtime, the compiler does not know that there is a cancel-function available and therefore compilation fails.
Note that if you aren't doing anything special, you should rather check for a common type/interface. So for example, if your objects implement an interface Cancellable you could just change your code to something as follows:
fun canceller(object: Any): KFunction<Any>? {
var canceller: KFunction<Any>? = null
// check if object is of type Cancellable
if (object is Cancellable) {
// make reference of the Cancellable::cancel-function
canceller = object::cancel // smart-cast acting
// or you could also call it directly: object.cancel()
}
return canceller
}
or probably you could just spare that function altogether and end up with something like just:
val someObj : Cancellable = ...
// somewhere later:
someObj.cancel()
Reflection is rather expensive and if you aren't entirely sure what it is useful for, you should not use it.
If you really knew what you were doing... then ok... it's of course also possible to call that function via reflection and if you ask for the existance of a function via reflection you also have to call it via reflection:
object::class.members.first {
// note: I am using just the first function... if there are several, you need to check which one to use (parameter/type)
it.name == "cancel"
}
.call(object)
I think you can use reflections for this purpose.
myObject.javaClass.kotlin.members.any { it.name == "cancel" }
And the better way to express the idea of "object that has all the variables" is to define the interface and have all those object implemented
interface Achiever { val name: String }

Interface function returning untyped value (*) while implementation return specific type?

Out of curiosity I was wondering if it was possible to have an interface definition returning untyped values, while its implementations return typed value ?
For example, having the following interface :
interfaceExample
{
function someExampleFunction():*
}
implemented the following way :
classA implements interfaceExample
{
public function someExampleFunction():Int{ ... }
}
classB implements interfaceExample
{
public function someExampleFunction():String{ ... }
}
( I've googled with no result, maybe I haven't been able to ask the right way )
I guess the answer is 'no it's not possible in any way, Interface aren't designed like that' -- so what could be a friendly way to achieve such a thing ?
You're right, this won't compile. This is because the compiler doesn't support overloading of the signature of methods from parent classes or interfaces.
If you think about it, it doesn't really make sense to override the return type when implementing an interface because the code consuming your interface API should not depend on the implementation (int or String return value).
The solution to use really depends on what you are trying to do in the end. In general, the return type should be the common denominator between the different types you could produce. This could also be another interface that describes what to expect from the return value.
While I'm not heavily familiar with interface definitions, I do know that I write a lot of functions that work with typed and untyped arguments and returns.
In the event that what you're describing is not possible, and depending on what you're doing, I would recommend writing a simple function that can convert an untyped variable into a typed variable. They're fairly simple. Then, you could call this function to handle whatever data comes in via the interface definition.
A rough example (untested):
function convertDataTo(type:String, input:*):*
{
var rI:int;
var rN:Number;
var rS:String;
var rB:Boolean;
switch(type)
{
case "int":
if(isNaN(int(input))
{
rI = 0;
}
else
{
rI = int(input);
}
break;
case "Number":
if(isNaN(Number(input))
{
rN = 0;
}
else
{
rN = Number(input);
}
break;
case "Boolean":
if(input == "true")
{
rB = true;
}
else if(input == "false")
{
rB = false;
}
else
{
rB = Boolean(input);
}
return rB;
break;
case "String":
rS = input.toString();
break;
default:
trace("Invalid data type!");
return 0;
break;
}
}
You can also rewrite this function to convert from String type to any other type, and have your interface definition always return strings. On the other end, you can have a similar function that converts all variables to strings that can be interpreted by this function.
By the way, I've had to use that kind of string interpretation in writing my own scripting language for use inside one of my larger projects.
Of course, I don't pretend this answers your question directly, but I wanted to throw out this contingency in case what you're looking for doesn't work.

Regarding variable initialization order

I'd like to know what's the default approach for those times when you need a variable to have been set in order for a given method/another variable initialization to work.
Like this:
Everything works if I initialize var A after var B. But not the other way around. I wrote the constructor, so I'll do that myself, but I'm not really sure where the code that tests for var B's existence should be. Or even if it should exist at all, for I have written the constructor and I initialize the values the order I see fit, but I feel it's a little insecure because it is not very robust in case anything changes.
Mind you, I'm talking about instance variables, if that helps.
FA
The answer can be influenced by the reason why a must be set before b.
Explicit Object Dependencies
If the reason is that b depends upon a, then the simplest thing to do is to make that dependency explicit at the time that b is created. For example, if a and b were objects then:
var a = new A(...);
var b = new B(a, ...);
var op = new Operation(b);
op.perform();
In this way, it is not possible to initialize the objects out of order. Note that A and B could be newly introduced wrapper objects that contain the original operation parameters.
Fluent Interface
If the reason is that the operation itself must know the value of a in order to perform some configuration in preparation for the arrival of b, then the operation constructor could be replaced by a fluent interface:
Operation op = Operation.withA(a).withB(b);
op.perform();
We must take care to define this fluent interface in such a way that withB can only be called after withA has been called. For example:
public class Operation {
private final C _c;
private final B _b;
private Operation(C c, B b) {
_c = c;
_b = b;
}
public static BStep withA(final A a) {
return new BStep() {
public Operation withB(B b) {
C c = setUpStateDependentUponA(a);
return new Operation(c, b);
}
};
};
public interface BStep {
Operation withB(B b);
}
public void perform() {
// do something with _c and _b
}
}
Here, C has been introduced to capture that state that is dependent upon a alone prior to the arrival of b. Note how the constructor of Operation is not visible to client code and that withB cannot possibly be called until after withA has been called.
I check before each time I access the variable, but if it is an instance variable and you initialize B in the constructor you should be safe. I use something like-
if (isset(var B)
{ do something with var A }
else
{ error handler }
or
try
{
if (isset(var B))
do something with a;
else
throw new Exception("attribute B has not been set.");
}
catch (Exception $e)
{
echo $e->getMessage();
return NULL;
}

How to define the return type of AS3 method that may return or not return a result?

public function t()
{
if(xxx)return xxx;
//don't return anything
}
How to define the return type for such method?
A function either has to return nothing, or return something - it can't do both. The reason being, what if you write this code:
var someValue = someFunction();
How would this code be handled if sometimes someFunction returned a value, and sometimes it didn't?
Your problem is a really common one, though, and there are several ways to work around it.
Sentinel Values
You can return special-case values that you treat as non-values (such as null, NaN, "", or -1). These special-case values are called sentinel values. The users of your function (maybe your own code) would check the result after calling it. If it gets one of the sentinel values back, it doesn't use the result.
Try-style Functions
You could also use a pattern commonly used in C#/.Net that they call "Try-methods", but you can call "Try-functions". Actionscript doesn't work exactly like C#, but we can get close enough for this pattern to work.
To do this, return Boolean, returning true if you have a value, and false if you don't. Then give your function an Object parameter, and populate a property with the actual return value:
function trySomeFunction(result:Object) : Boolean
{
if(xxx)
{
result.Value = xxx;
return true;
}
return false;
}
// ...
var result:Object = { Value:null };
if(trySomeFunction(result))
{
// Do something with the value here
}
Exceptions
If your method failed to do what it promised to do, you can throw an exception. Then you don't have to worry about what gets returned, because your code just dies.
Exceptions are great because people who call your code don't have to learn as much. They don't have to know that your function only succeeded if it doesn't return some magic value that is different for every function, they don't need to check if your function returns true/false, and they don't need to know that some property gets populated on an object when the function succeeded.
Without exceptions, if they forget to check for your special value, or the result of a "Try-function", an error might happen further on in the program. Or it might not happen at all, and the program will continue running, but be broken. In these cases, it is much harder to track down the problem.
With exceptions, your code just blows up the second it detects a problem, and gives you the line of code where your program realized it couldn't work correctly.
If it is normal and okay for your function to fail, though, you probably shouldn't throw an exception. You should probably use a "Try-function" or a sentinel value instead.
Everything that Merlyn says is fine, though perhaps a bit of overkill. If your method needs the potential to return null, then just pass xxx back whether it's null or not...
public function t():MyReturnType
{
return xxx;
}
... since you're going to have to do check the special condition in the calling method anyway:
public function caller():void
{
var value:MyReturnType = t();
if (value)
doSomethingPositive();
else
copeWithNullState();
}
Some people think that this is wrong and advocate creating a special 'null value' object in your return class, like this:
public class MyReturnType
{
public static const NULL:MyReturnType = new MyReturnType(null);
public function MyReturnType(identifier:String)
...
}
then in your function either return an interesting MyReturnType or NULL:
public function t():MyReturnType
{
return xxx || MyReturnType.NULL;
}
but then you've not really improved your caller method so why bother?
public function caller():void
{
var value:MyReturnType = t();
if (value != MyReturnType.NULL)
doSomethingPositive();
else
copeWithNullState();
}
Whatever you choose to do, eventually you're just going to have to test for special cases in the caller method. Personally I'd say it's better to keep it as simple as possible, and the special 'null value' in your class is over-complication.
I write plenty of functions that might return an object reference, but may also return null, like this:
public function findThingById( id:int ):MyThingType
{
... code here to search for/load/lookup thing with matching id
if (found)
{
return thing;
}
return null;
}
Wherever you call a function that might return null, you would either test the return value for null explicitly, or if you expect null just don't do anything with the return value. For built-in data types, you would use a special value rather than null (like NaN for Numbers illustrated above), but the principle is the same.
public function t():type
{
if(xxx)return xxx;
//don't return anything
}
so something like:
private function derp():void{
}
private function derp2():int{
}
private function derp3():Boolean{
}
etc
its always good practice to define the return type, and return an indicator variable if false (i.e return -1 for number), but if its really necessary you can do this:
public function t()
{
if(xxx)return xxx;
//don't return anything
}
don't specify a return type at all, and either it will return xxx or undefined, but I highly encourage using a return type.
But since flash runs on virtual memory it can basically adapt to your return type so it makes it a little flexible so you can return what ever.
EDIT:
public function t()
{
if(true){
return xxx; //xxx can by of any type
}
return NaN
}
EDIT:
so lets say you want the condition with a return type of int you would have
public function t():int
{
if(true){
return xxx; //where xxx != -1
}
return -1
}
this when we get back any number other then negative 1 we know the condition was true, but if we get -1 the condition was false. But if you numbers are any real numbers, use NaN keyword:
public function t():Number
{
if(true){
return xxx; //where xxx != -1
}
return NaN
}
this way if you get NaN back it means your condition was false
I should also mention that when your dealing with NaN use the isNaN() to determine if the return type was NaN or not:
example:
if(isNaN(t()) == true){
//if condition in function t() was false;
}
There is no way a single function can return void as well as returning a type. This is because void is not part of any inheritance chain, it is a top level concept meaning something very specific; it doesn't return anything.
Don't get confused between null and void, undefined and void, NaN and void. They are different concepts.
The answer to your question is simply that it can't, nor should it be done. When you hit a problem like this, it's good practice to step back and ask 'why' do you need to do this.
I would highly encourage that you mark this question as closed, and instead posted a higher level problem. For example,
How would I structure a class that has a variable xxx that does this and that and will be eventually set to a number when the user clicks. But if the user never clicks, it will be unset.... ecetera ecetera....
If you are 100% convinced you should do something like you're asking, you could 'fake' it by
function f():* {
var xxx:Number = 999;
if(xxx) {
return xxx;
} else {
return undefined;
}
}
var xx:* = f();
trace(xx);
But remember, from that point onwards you will need to check everytime xx is used to see if it undefined. Otherwise it will lead to errors.

What are some uses of closures for OOP?

PHP and .Net have closures; I have been wondering what are some examples of using closures in OOP and design patterns, and what advantages they have over pure OOP programming.
As a clarification, this is not a OOP vs. functional programming, but how to best use closures in a OOP design. How do closures fit in, say, factories or the observer pattern? What are some tricks you can pull which clarify the design and results in looser coupling, for example.
Closures are useful for event-handling. This example is a bit contrived, but I think it conveys the idea:
class FileOpener
{
public FileOpener(OpenFileTrigger trigger)
{
trigger.FileOpenTriggered += (sender, args) => { this.Open(args.PathToFile); };
}
public void Open(string pathToFile)
{
//…
}
}
my file opener can either open a file by directly calling instance.Open(pathToFile), or it can be triggered by some event. If I didn't have anonymous functions + closures, I'd have to write a method that had no other purpose than to respond to this event.
Any language that has closures can use them for trampolining, which is a technique for refactoring recursion into iteration. This can get you out of "stack overflow" problems that naive implementations of many algorithms run into.
A trampoline is a function that "bounces" a closure back up to its caller. The closure captures "the rest of the work".
For example, in Python you can define a recursive accumulator to sum the values in an array:
testdata = range(0, 1000)
def accum(items):
if len(items) == 0:
return 0
elif len(items) == 1:
return items[0]
else:
return items[0] + accum(items[1:])
print "will blow up:", accum(testdata)
On my machine, this craps out with a stack overflow when the length of items exceeds 998.
The same function can be done in a trampoline style using closures:
def accum2(items):
bounced = trampoline(items, 0)
while (callable(bounced)):
bounced = bounced()
return bounced
def trampoline(items, initval):
if len(items) == 0:
return initval
else:
return lambda: trampoline(items[1:], initval+items[0])
By converting recursion to iteration, you don't blow out the stack. The closure has the property of capturing the state of the computation in itself rather than on the stack as you do with recursion.
Suppose you want to provide a class with the ability to create any number of FileOpener instances, but following IoC principles, you don't want the class creating FileOpeners to actually know how to do so (in other words, you don't want to new them). Instead, you want to use dependency injection. However, you only want this class to be able to generate FileOpener instances, and not just any instance. Here's what you can do:
class AppSetup
{
private IContainer BuildDiContainer()
{
// assume this builds a dependency injection container and registers the types you want to create
}
public void setup()
{
IContainer container = BuilDiContainer();
// create a function that uses the dependency injection container to create a `FileOpener` instance
Func<FileOpener> getFileOpener = () => { return container.Resolve<FileOpener>(); };
DependsOnFileOpener dofo = new DependsOnFileOpener(getFileOpener);
}
}
Now you have your class that needs to be able to make FileOpener instances. You can use dependency injection to provide it with this capability, while retaining loose coupling
class DependsOnFileOpener()
{
public DependesOnFileOpener(Func<FileOpener> getFileOpener)
{
// this class can create FileOpener instances any time it wants, without knowing where they come from
FileOpener f = getFileOpener();
}
}