Simple Framework with Getters and Setters in Android - simple-framework

I'm new to Simple Framework, but I didn't find any advice about the use of the Getters/Setters knowing that they are not good in Android for performance point of view.
http://developer.android.com/training/articles/perf-tips.html#GettersSetters
Is there a way to not use them in Simple-Framework ?

My answer will probably be better with code samples, but pretty much. Whenever you are dealing with the field within the class, try to use the actual variable vs a method.
example. Within your class, you would use it like the following:
public class Foo
{
public Object bar; // This would be private if I was using a getter
public void doSomeStuff()
{
if(bar)
{
//work the bar
}
}
public Object getBar()
{
return bar;
}
}
Then externally, it would be used like this:
public class OtherFoo
{
public void somethingElse()
{
Foo ob = new Foo();
inner = ob.getBar();
}
}
External getters are a pro/con here, as they do break the performance rule stated, but they promote much better practices (preserved encapsulation, less nasty coupling, better maintainability, etc).
This all being said though, this performance tip can be taken with a grain of salt, since Android devices have gotten more and more powerful (in fact, I'm very certain this performance hit has almost been removed as of GingerBread).
My personal recommendation is to follow OOP principle, and use getters when possible, unless there is a serious performance issue.

Related

Is it bad to wrap singleton instance methods in static methods?

Is there a con to implementing a singleton that wraps instance methods with static ones?
For example:
public void DoStuff() { instance._DoStuff(); }
private void _DoStuff() {
...
}
And of course instance would be static. But it would be nicer to call:
Singleton.DoStuff();
Instead of:
Singleton.GetInstance().DoStuff();
I think it depends.
First the GetInstance() really should be used for getting an object back and then using that else where in your code. The Singleton should just help guarantee a single instance of that object exists.
Next if you want to make DoStuff static go ahead, though you have to know to call it that way everywhere else in your code.
So you really have this difference:
var instance = Singleton.GetInstance();
...
instance.DoStuff ()
Vs
Singleton.DoStuff ()
This means that you can pass a singleton object around and not have to know static calls.
Also, I have to mention that Singletons if not used properly can lead to a nightmare in unit testing: http://misko.hevery.com/2008/08/25/root-cause-of-singletons/

Is there a #visibility package concept in PHPDoc / PHPStorm?

I have a domain model written in PHP, and some of my classes (entities inside an aggregate) have public methods, which should never be called from outside the aggregate.
PHP does not have the package visibility concept, so I'm wondering if there is some kind of standardized way to define #package and #visibility package in the docblocks, and to have a static analysis tool that would report violations of the visibility scope.
I'm currently trying out PHPStorm, which I've found very good so far, so I'm wondering if this software has support for this feature; if not, do you know any static code analysis tool that would?
The closest parallel to this line of thinking that I see in PHP's capability is using "protected" scope rather than public for these kinds of methods. Granted, that requires using inheritance to grant access to the protected items. In my years of managing phpDocumentor, I've never encountered anything else that attempts to mimic that kind of "package scope" that I remember from my Java days.
If the entities within your aggregate root should not be modifiable without going through the aggregate root, then the only means you have to control that is making the entity a private or protected member so that all modifications to the entity have to go through the aggregate.
class RootEntity {
private $_otherEntity;
public function DoSomething() {
$this->_otherEntity->DoSomething();
}
public function setOtherEntity( OtherEntity $entity ) {
$this->_otherEntity = $entity;
}
}
Someone can still always do:
$otherEntity = new OtherEntity();
$otherEntity->DoSomethingElse();
$rootEntity->setOtherEntity($otherEntity);
Though, I guess you could use the magic __call() method to prohibit setting of the _otherEntity anywhere except during construction. This falls under total hack category :)
class RootEntity {
private $_otherEntity;
private $_isLoaded = false;
public function __call( $method, $args ) {
$factoryMethod = 'FactoryOnly_'.$method;
if( !$this->_isLoaded && method_exists($this,$factoryMethod) {
call_user_func_array(array($this,$factoryMethod),$args
}
}
public function IsLoaded() {
$this->_isLoaded = true;
}
protected function FactoryOnly_setOtherEntity( OtherEntity $otherEntity ) {
$this->_otherEntity = $otherEntity;
}
}
So, from there, when you build the object, you can call $agg->setOtherEntity($otherEntity) from your factory or repository. Then when you are done building the object, call IsLoaded(). From there, nobody else will be able to introduce a new OtherEntity into the class and will have to use the publicly available methods on your aggregate.
I'm not sure if you can call that a "good" answer, but it's the only thing I could think of to truly limit access to an entity within an aggregate.
[EDIT]: Also, forgot to mention...the closest for documentation is that there is an #internal for phpdoc:
http://www.phpdoc.org/docs/latest/for-users/tags/internal.html
I doubt that it will modify the IDE's code completion, however. Though, you could probably make a public function/property but label it as "#access private" with phpdoc to keep it from being in code completion.
So far, PHPStorm does not seem to provide this feature.

Static and Normal class combined in one class

I am trying my best to explain the situation. I hope, what I wrote, is understandable.
We already have class defined like
public ref class TestClass
{
public:
TestClass();
virtual ~TestClass();
protected:
Car* m_car;
}
TestClass is managed C++ and Car is unmanaged C++.
So far so good, but now I need to make static object of TestClass also. So I modify the code like below
public ref class TestClass
{
private:
static TestClass^ s_test = nullptr ;
public:
TestClass();
virtual ~TestClass();
static TestClass^ Instance();
protected:
Car* m_car;
}
When I want to use static instant of the class, I just get it from calling
TestClass staticobj = TestClass::Instance();
Elsewhere, just call
TestClass normalobj = gcnew TestClass();
Instance function is creating s_test static object and returns it.
TestClass ^ TestClass::Instance()
{
if(s_test == nullptr)
{
s_test = gcnew TestClass();
s_test->m_car = new Car();
}
return s_test;
}
Is it a good approach?
Is there any other better approach to accomplish same thing?
Edit :
FYI Above code works.
I combined Krizz and Reed Copsey’s solutions. That solve independent Singleton and memory leak.
Here is my sample code,
Special Singleton class derived from test class,
public ref class SpecialSingletonTestClass: public TestClass
{
private:
static SpecialSingletonTestClass ^ s_ SpecialSingletonTestClass = nullptr;
public:
SpecialSingletonTestClass ();
static SpecialSingletonTestClass ^ Instance();
};
Changed the testclass so it has now one more finalizer function.
public ref class TestClass
{
public:
TestClass ();
virtual ~ TestClass ();
! TestClass ();
protected:
Car* m_car;
}
I tested above pattern , it worked.
Thanks you guys,
L.E.
Is it a good approach?
I would probably not consider this a good approach, as you're making a single class both a singleton and a normal class that you can instance directly.
Typically, if you need a singleton, this would preclude the need or desire to be able to instantiate the class.
If you truly need to have a way to have a "global" instance of this class, I would encapsulate that in a separate class which implements the singleton. This would, at least, make it clear that you are dealing with something that's a single instance in that case. I would not mix both use cases into a single class.
Well, actually there is an issue with memory leaks in your code.
You declare only virtual ~TestClass(); which, for managed classes, are internally turned by C++/CLI compiler into implementation of IDisposable.Dispose().
Therefore, if you put delete car into it, it will be called only if you delete test_class or, e.g. wrap into using (TestClass tst) {} block when using from C#.
It will not be called when object is GCed!
To be sure it is called you need to add finalizer to your class !MyClass(); which is turned by compiler into virtual void Finalize() and thus non-deterministically called when GC is freeing an object.
And it is the only way to free m_car of singleton object.
Therefore, I suggest:
TestClass()
{
m_car = new Car();
}
~TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
!TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
I'm unsure as to what situation you could possibly be in that would require both singleton-style semantics and normal creation semantics for the same class.
As far as what you've coded though, it looks completely fine. My only comments would be that your Instance() function shouldn't need to perform construction on Car, the Instance() function should just call the default constructor of TestClass which should do all that.
EDIT
In reference to:
#crush . The class is already define i just need to get static object of it. Singleton means only one object of the class, but in this case, class have multiple normal object. But i want to use only one object of this class for one specific goal only for limited period of time. – L.E. 2 mins ago
A singleton is (usually) a sign of bad design - alot of people call it an anti-pattern actually. Chances are if you just need this one single specific instance of this class for a limited period of time there are some issues:
Singleton design is made for static-style existence - the variable will live for the scope of your program after lazily initialized.
Allowing global access will move your code towards spaghetti logic. You'd be better off dynamically allocating the one you need and passing the pointer to it to where you need it to be. A shared_ptr would be good for this.
You should find a way around the singleton-style implementation in this case even if it's more work for you - it'll almost certainly be better design.

In php we can access static member functions using class objects. Can someone please tell any practicle use of this feature

In php we can call static member functions using class objects. For example
class Human
{
public static function Speak()
{
echo "I am a human.";
}
}
$human = new Human();
$human->Speak();
What we would expect is that a static member function can only be called using the class name and not the class instance variable (object). But what i have seen while programming is that php allows calling a static member function using the class object also. Is there any practical use or some important reason that this feature has been provided in php ?
This feature exists in java and c++ also. Thanks Oli for pointing this out in your response.
This is the same as in other OO languages, such as C++ and Java. Why would you want the interpreter to prevent this?
UPDATE
My best guess for this (and this is only a guess) is "for convenience". In essence, why should the user of your class necessarily care whether a given member function is static or not? In some circumstances, this will certainly matter; in others, maybe not. I'm not saying this is a great justification, but it's all I can come up with!
it allows you to abstract from the particular definition of the method, so that for example if you had to turn it into a static one at some point, you don't have to rewrite all the method calls!
I can't answer for PHP, (or really for anything) but consider this hypothetical C++:
class base{
public:
static void speak(){cout<<"base\n";}
};
class sub :public base {
public:
static void speak(){cout<<"sub\n"; }
};
int _tmain(int argc, _TCHAR* argv[]){
base *base1 = new base();
base1->speak();
sub *sub1 = new sub();
sub1->speak();
base *sub2 = new sub();
sub2->speak();
((sub*)sub2)->speak();
}
The output would be:
base
sub
base
sub
I'm sure it could be useful... maybe helping you determine which class's static method you should call based on the object currently in hand.

typesafe NotifyPropertyChanged using linq expressions

Form Build your own MVVM I have the following code that lets us have typesafe NotifyOfPropertyChange calls:
public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
{
var lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else memberExpression = (MemberExpression)lambda.Body;
NotifyOfPropertyChange(memberExpression.Member.Name);
}
How does this approach compare to standard simple strings approach performancewise? Sometimes I have properties that change at a very high frequency. Am I safe to use this typesafe aproach? After some first tests it does seem to make a small difference. How much CPU an memory load does this approach potentially induce?
What does the code that raises this look like? I'm guessing it is something like:
NotifyOfPropertyChange(() => SomeVal);
which is implicitly:
NotifyOfPropertyChange(() => this.SomeVal);
which does a capture of this, and pretty-much means that the expression tree must be constructed (with Expression.Constant) from scratch each time. And then you parse it each time. So the overhead is definitely non-trivial.
Is is too much though? That is a question only you can answer, with profiling and knowledge of your app. It is seen as OK for a lot of MVC usage, but that isn't (generally) calling it in a long-running tight loop. You need to profile against a desired performance target, basically.
Emiel Jongerius has a good performance comparrison of the various INotifyPropertyChanged implementations.
http://www.pochet.net/blog/2010/06/25/inotifypropertychanged-implementations-an-overview/
The bottom line is if you are using INotifyPropertyChanged for databinding on a UI then the performance differences of the different versions is insignificant.
How about using the defacto standard
if (propName == value) return;
propName = value;
OnPropertyChanged("PropName");
and then create a custom tool that checks and refactors the code file according to this standard. This tool could be a pre-build task, also on the build server.
Simple, reliable, performs.
Stack walk is slow and lambda expression is even slower. We have solution similar to well known lambda expression but almost as fast as string literal. See
http://zamboch.blogspot.com/2011/03/raising-property-changed-fast-and-safe.html
I use the following method in a base class implementing INotifyPropertyChanged and it is so easy and convenient:
public void NotifyPropertyChanged()
{
StackTrace stackTrace = new StackTrace();
MethodBase method = stackTrace.GetFrame(1).GetMethod();
if (!(method.Name.StartsWith("get_") || method.Name.StartsWith("set_")))
{
throw new InvalidOperationException("The NotifyPropertyChanged() method can only be used from inside a property");
}
string propertyName = method.Name.Substring(4);
RaisePropertyChanged(propertyName);
}
I hope you find it useful also. :-)
Typesafe and no performance loss: NotifyPropertyWeaver extension. It adds in all the notification automatically before compiling...

Resources