onPropertyChanged - How to switch propertyId from external class - android-databinding

I have a model that extends BaseObservable. I have a view model that contains a reference to the model and subscribes to property changes within the model. How do I switch on the Model.propertyId from within the callback in the view model? In the sample below BR.assignedId is the property in the model. For example:
View Model
public void onPropertyChanged(Observable sender, int propertyId)
{
switch (propertyId)
{
case MyModel.BR.assignedId://compile error
notifyPropertyChanged(BR.assignedImage);
break;
}
}

I suggest you to read Observer pattern. The code above has Entities : Observer and Observable. Observer has an Observing method. Any class which wants to observe the 'Observable' needs to register itself as 'Observer'. Observable calls the observing method on the Observer and this is how the usual call back works. (names of classes and methods may be differnt , I used as per the intent and context)
Check 'ViewModel.java' class would be implementing some 'observer' interface which would be having the method 'onPropertyChanged ()'. you will have to set the object of ViewModel.java in Model.java. (check you should be having a method with a name like addPropertyChangeObserver (), though it may be differnt but similar method. Use this method to set the object of ViewModel.java in Model.java. Now Model.java would call the method 'onPropertyChanged' on ViewModel.java.
if you wish to modify something on the Model then check the sender parameter. You can add another method in the interface implemented by Model and can do modifications on Model using it or can simply typecast the sender after checking its type with instanceof and can perform the process on Model.java from the callback method.

Related

LoD: calling components` components - allowed or not?

Is it allowed to call components' components according to the Law of Demeter?
By component I mean an object
which was "exclusively" injected into the container or was created in
the container
which has the same life cycle with it's container
For example, Brain is a component of a Dog:
partial class Dog
{
private readonly IBrain brain;
public Dog(IBrain brain)
{
this.brain = brain;
}
}
Here is some information I found:
http://c2.com/cgi/wiki?LawOfDemeter
Your method can call methods on its own fields directly (but not on
the fields' fields)
message target can only be one of the following objects:
... an object referred to by the object's attribute
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
A method of an object should invoke only the methods of the following
kinds of objects:
...
any objects it creates/instantiates
its direct component objects
And here is a case:
partial class Dog
{
public void Command(string cmd)
{
var movement = brain.GetMemory().GetMovement(cmd);
skeleton.ExecuteMovement(movement);
}
}
Is it allowed to call components' components according to the Law of Demeter?
By definition this is not allowed since you should Only talk to your immediate friends.
In other words, the IBrain service should not expose its internal services through its interface (assuming that GetMemory() returns an IMemory service of some kind). Instead, the IBrain interface should either provide provide a method that allows retrieving the movement -or- the IMemory should be injected directly intoDog`.

OO Design Issue related to subclassing

I have a parent bean having one instance variable like below :
public Class ParentBean {
protected boolean show; // this variable will be used to show some UI component
public void action() {
// update show variable here
}
public boolean isShow() {
return show;
}
}
Is it a good design if I want to reuse the "show" variable in a child bean (to show other UI component specific to child bean ) as shown below :
public Class ChildBean extends ParentBean {
// override the action method from parent bean
public void action() {
// update show variable here
show = true /false;
}
}
In effect , show variable is being updated by "childBean" by overriding action() method.
Is this a good design practice ? Otherwise same thing has to be repeated in ChildBean to get this work done.
If you use the show variable for the same purpose in the subclass, as you seem to be doing in this example, then obviously you should reuse it, because otherwise you just end up writing the same code twice, which is contrary to the point of OOP.
In general, in OOP, it is common to override superclass methods in subclasses, as well as modifying superclass instance variables, as long as you know what the variable you are modifying is being used for (you don't want to be randomly changing instance variables in classes that you don't completely understand, or don't have access to the source of, because you don't want any unfortunate side effects), so when it's your own code, this is absolutely fine.
As a general guideline, if your options are either to copy and paste a massive hunk of code and use it unchanged, or subclass and use the superclass' instance variables or functions, it's better to subclass. Otherwise, you're missing out on the point of OOP.
Changing the value in subclass will not affect superclass variable
This is fine with respect to the design. When a subclass object is instantiated, it will have a different copy of variable. and If superclass object is instantiated it will have different copy.
It is. Having a protected variable means you are allowed to modify it into parent or children classes (remember every single instance of each class has its own property values). So, if you have some generic functionality which is valuable for all the children:
Parent class:
public void action(){
//update show variable here
show = true;
}
Appart from that, if you want to add some extra functionality in a specifical child:
Child class:
#Override
public void action(){
super.action();
//Extra functionality goes here
//You can also access parent's 'protected' fields
if (show){
System.out.println("Shown");
}
}
An example of the use:
Parent p = new Parent();
p.action();//Prints nothing
Child c = new Child();
p.action();//Prints 'shown'

groovy method scope when using a method reference

I have a groovy class that looks up a method reference and then invokes it. The method being invoked is a private method. When the actual class is an instance of the child class, it throws an error that it cannot find the private method, even though it is the public method in the parent that actually calls it.
In this case, I could obviously just call pMethod2() directly and that works, but I'm trying to understand why this doesn't work as written and if there's a way to correct it so it works.
class Parent {
def pMethod1() {
def m = this.&pMethod2
m() // this call fails if the calling class is of type Child
}
private def pMethod2() {}
public static void main(String[] args) {
new Child().pMethod1();
}
}
class Child extends Parent {}
It is a bit confusing, especially if you're used to C / C++. What you get when using the ".&" operator in Groovy is not an address, but an instance of MethodClosure.
The MethodClosure object contains an owner and a delegate object, which is used when resolving the method to call. In your example, the owner and delegate object will be "this", which is an instance of Child. The method to call is simply stored as a string.
So, the assignment
m = this.&pMethod2
is just a shorthand way of writing
m = new MethodClosure(this, "pMethod2")
When you invoke the m() closure, it will try to resolve (at runtime) the method by looking for methods named "pMethod2" in the owner and the delegate objects respectively. Since the owner and delegate is an instance of Child, it will not find private methods located in Parent.
To make your example work you must make sure that the method is visible to the owner and/or delegate of the closure.
This can be done several ways, for instance by changing the access modifier of pMethod2 to protected, or by creating the closure with an instance of Parent; something like this:
m = new Parent().&pMethod2
Note that is is irrelevant that you created the MethodClosure instance in a method where pMethod2 is actually visible. It is also irrelevant that you invoke the closure in a method where it is visible. The method is not visible to the owner or delegate of the MethodClosure, which is what is being used when resolving the method.

In MVC, is a controller an object or a function?

I am learning Symfony2, and part of the documentation on controllers states that the methods on the controller object are actually the controllers, whereas the object is more of a controller container.
Which part specifically is referred to as the controller(s)? I'm new to MVC and OOP, so I'm just trying to make sure I have it right.
the page describes actually a convention endorsed by Symfony2 creators.
in some MVC frameworks (esp. in Java) controllers are implemented by one-class-per-controller convention, e.g.:
class ListContactsController {
public function start() {
// query db...
return ...;
}
}
class AddContactController {
public function start($name, $details) {
// insert into db...
return ...;
}
}
note that every controller-class has one method start() that defines what the controller actually does
in other MVC frameworks (like Symfony2 or cake-php) controllers are implemented by one-method-per-controller convention, grouped together for convenience, e.g.:
class ContactsController {
public function list() {
// query db...
return ...;
}
public function add($name, $details) {
// insert into db...
return ...;
}
}
here the convention assumes every controller is implemented as a method rather than a separate class with a particular method like start()
EDIT: another way of thinking about this difference is this:
one-class-per-controller assumes there is one controller instance (might hold internal state) and when user interacts with the view, view is communicating with that controller instance via callbacks i.e. methods in controller's class.
one-method-per-controller assumes any state is contained within parameters that are passed to methods, and when user interacts with the view, view is communicating with separate controllers/actions. those controllers are seen as independent concepts.
In the example page you shared, the "class HelloController" is the Controller and its' functioned are Controller "Methods".
Okay, they are referring to the default method, indexAction() as the Controller.
In this MVC architecture (and most others, if not all) the "index" method is the default method (function) called when that controller is requested.

What is Delegate? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am confused that what is the actual role of a delegate?
I have been asked this question many times in my interviews, but I don't think that interviewers were satisfied with my answer.
Can anyone tell me the best definition, in one sentence, with a practical example?
I like to think of a delegate as "a pointer to a function". This goes back to C days, but the idea still holds.
The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose. Delegates come in handy for things like event handlers, and such, where you do different things based on different events, for example.
Here's a reference for C# you can look at:
In C#, for example, let's say we had a calculation we wanted to do and we wanted to use a different calculation method which we don't know until runtime. So we might have a couple calculation methods like this:
public static double CalcTotalMethod1(double amt)
{
return amt * .014;
}
public static double CalcTotalMethod2(double amt)
{
return amt * .056 + 42.43;
}
We could declare a delegate signature like this:
public delegate double calcTotalDelegate(double amt);
And then we could declare a method which takes the delegate as a parameter like this:
public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
return calcTotal(amt);
}
And we could call the CalcMyTotal method passing in the delegate method we wanted to use.
double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
Console.WriteLine(tot1);
Console.WriteLine(tot2);
a delegate is simply a function pointer.
simply put you assign the method you wish to run your delegate.
then later in code you can call that method via Invoke.
some code to demonstrate (wrote this from memory so syntax may be off)
delegate void delMyDelegate(object o);
private void MethodToExecute1(object o)
{
// do something with object
}
private void MethodToExecute2(object o)
{
// do something else with object
}
private void DoSomethingToList(delMyDelegate methodToRun)
{
foreach(object o in myList)
methodToRun.Invoke(o);
}
public void ApplyMethodsToList()
{
DoSomethingToList(MethodToExecute1);
DoSomethingToList(MethodToExecute2);
}
Taken from here
Q What are delegates?
A When an object receives a request, the object can either handle the request itself or pass the request on to a second object to do the work. If the object decides to pass the request on, you say that the object has forwarded responsibility for handling the request to the second object.
Or, as an easy pseudo example: something sends a request to object1. object1 then forwards the request and itself to object2 -- the delegate. object2 processes the request and does some work. (note: link above gives good examples)
Think about delegate as about a simplified implementation of Command pattern.
A delegate is an object that can refer to a method. Thus, when we create a delegate, we are creating an object that can hold a reference to a method. Furthermore, the method can be called through this reference. Thus, a delegate can invoke the method to which it refers.
The principal advantage of a delegate is that it allows us to specify a call to a method, but the method actually invoked is determined at runtime, not at compile time.
Simple Delegate
Declaration of delegate:
delegate-modifier delegate return-type delegate-name(parameters)
Implementation of delegate:
Delegate-name delegate-object=new Delegate-name(method of class)
http://knowpacific.wordpress.com/2012/01/26/delegate/
Here I am going to explain delegates, multicast delegates and their usage..
Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. We can say a delegate is a type that defines a method signature.
When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance.
Delegates are used to pass methods as arguments to other methods.
Event handlers are nothing more than methods that are invoked through delegates.
Advantages of using delegates are,
Encapsulating the method's call from caller
Effective use of delegate improves the performance of application
Used to call a method asynchronously.
There are some properties of delegates are
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.
public delegate type_of_delegate delegate_name() // Declaration
You can use delegates without parameters or with parameter list
If you are referring to the method with some data type then the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer. Here I am giving an example with String.
The following example shows a delegate operation:
namespace MyDelegate
{
class Program
{
private delegate void Show(string s);
// Create a method for a delegate.
public static void MyDelegateMethod(string me
ssage)
{
System.Console.WriteLine(message);
}
static void Main(string[] args)
{
Show p = MyDelegateMethod;
p("My Delegate");
p.Invoke("My Delegate");
System.Console.ReadLine();
}
}
}
What is Multicast Delegate?
It is a delegate which holds the reference of more than one method. Multicast delegates must contain only methods that return void, else there is a run-time exception.
delegate void MyMulticastDelegate(int i, string s);
Class Class2
{
static void MyFirstDelegateMethod(int i, string s)
{
Console.WriteLine("My First Method");
}
static void MySecondDelegateMethod(int i, string s)
{
Console.WriteLine("My Second Method");
}
static void Main(string[] args)
{
MyMulticastDelegate Method= new MyMulticastDelegate(MyFirstDelegateMethod);
Method+= new MyMulticastDelegate (MySecondDelegateMethod);
Method(1,"Hi"); // Calling 2 Methodscalled
Method-= new MyMulticastDelegate (MyFirstDelegateMethod);
Method(2,"Hi"); //Only 2nd Method calling
}
}
Here Delegate is added using the += operator and removed using the -= operator.
Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed—they cannot be derived.
Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback.
A great explanation and practical implementation of the Delegate pattern can be found in the Google Collections Forwarding Classes (also, the Decorator pattern).
In Event communication sender does not know which object will handle the event.
Delegate is type which hold the reference of method.
Delegate has signature and holds reference to method which matches its signature
so Delegate is like type safe function pointer.
button1.Click += new System.EventHandler(button1_Click)
System.EventHandler is declared as a delegate here
In .net Events work on the concept of Delegate (like Button Click)
Delegate is used when you do not know which code to invoke at run time
So at that time Delegate is used to handle Events
http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx
A delegate object
is an object that another object consults when something happens in that object. For
instance, your repair man is your delegate if something happens to your car. you go to your repair man and ask him to fix the car for you (although some prefer to repair the car themselves, in which case, they are their own delegate for their car).
A delegate is an object that represents a pointer to a function. However, it is not an ordinary function pointer in that it:
1) Is Object Oriented
2) Is type safe, i.e. it can only point to a method and you cannot read the raw memory address it is pointing to
3) Is strongly typed. It can only point to methods that match its signatures.
4) Can point to more than one method at the same time.
Delegates is mainly used with events.
The need is:
You do not want to execute a piece of code at the time when you run the program.
After running the program you want to execute that piece of code whenever an event occurs.
Example :
Console application - code can be executed only at the time you run the program. (Written inside Main method)
Windows application (user interface programming ) - code can be executed when clicking the button after running the program.
This is what they say, you do not know which method will invoke at compiling time. you know it only at runtime that is when clicking the button.
Without delegates no user interface programming is possible. Because you are executing code whenever the user makes events that is clicking button , typing in textbox, selecting dropdownlist item and so on....
A delegate is something to which a task is being delegated. The primary purpose of delegation is to decouple code and allow for greater flexibility and reuse.
In programming, and specifically object-oriented programming, this means that when a method is called to do some work, it passes the work on to the method of another object that it has a reference to. The reference could point to whatever object we wish, as long as the object conforms to a predefined set of methods. We call it "programming to an interface" (versus programming to a concrete class implementation). An interface is basically a generic template and has no implementation; it simply means a recipe, a set of methods, preconditions and postconditions (rules).
Simple example:
SomeInterface
{
public void doSomething();
}
SomeImplementation implements SomeInterface
{
public void doSomething()
{
System.err.println("Was it good for you?");
}
}
SomeCaller
{
public void doIt(SomeInterface someInterface)
{
someInterface.doSomething();
}
}
Now you see I can use whatever implementation I want at any time without changing the code in SomeCaller because the type that doIt() is passed is not concrete but rather abstract since it's an interface. In the Java world, this is often expressed in the service paradigm where you call out to a service (an object advertising itself as a service via a specific interface) and the service then calls out to delegates to help it do its work. The service's methods are named as coarse-grained tasks (makePayment(), createNewUser(), etc.), while internally it does lots if nitty-gritty work through delegation, with the delegates' types being interfaces instead of the concrete implementations.
SomeService
{
SomeInterface someImplementation = ... // assign here
SomeOtherInterface someOtherImplementation = ... // okay, let's add a second
public void doSomeWork()
{
someImplementation.doSomething();
someOtherImplementation.doSomethingElse();
}
}
(N.B.: How an implementation gets assigned is beyond the scope of this thread. Lookup inversion of control and dependency injection.)
While not really a "function pointer", a delegate might look like this is a dynamic language like PHP:
$func = 'foo';
$func();
function foo() {
print 'foo';
}
or in JavaScript you could do something like:
var func = function(){ alert('foo!'); }
func();