If you extend SingletonCachedBizlet, do you need to override the newInstance() method - skyve

If you are not doing any default values or anything other than using the SingletonCachedBizet to retrieve the singleton record, do you need to override the newInstance() method?

No, the default behaviour is inherited and handles retrieving and caching the singleton instance for the document specified in your Bizlet. For example, for a Settings document, this is a sufficient complete definition:
public class SettingsBizlet extends SingletonCachedBizlet<Settings> {
// optional depending on your compiler warnings
private static final long serialVersionUID = 7837583728201289659L;
}

Related

PowerMock: mock out private static final variable, a concrete example

what is the absolute minimal mocking that must be done to pass this test?
code:
class PrivateStaticFinal {
private static final Integer variable = 0;
public static Integer method() { return variable + 1; }
}
test:
#RunWith(PowerMockRunner.class)
#PrepareForTest(PrivateStaticFinal.class)
class PrivateStaticFinalTest {
#Test
public void testMethod() {
//TODO PrivateStaticFinal.variable = 100
assertEquals(PrivateStaticFinal.method(), 101);
}
}
related: Mock private static final variables in the testing class (no clear answer)
Disclaimer: After a lot of hunting around on various threads I have found an answer. It can be done, but the general concensus is that it is not very safe but seeing as how you are doing this ONLY IN UNIT TESTS, I think you accept those risks :)
The answer is not Mocking, since most Mocking does not allow you to hack into a final. The answer is a little more "hacky", where you are actually modifying the private field when Java is calling is core java.lang.reflect.Field and java.lang.reflect.Modifier classes (reflection). Looking at this answer I was able to piece together the rest of your test, without the need for mocking that solves your problem.
The problem with that answer is I was running into NoSuchFieldException when trying to modify the variable. The help for that lay in another post on how to access a field that was private and not public.
Reflection/Field Manipulation Explained:
Since Mocking cannot handle final, instead what we end up doing is hacking into the root of the field itself. When we use the Field manipulations (reflection), we are looking for the specific variable inside of a class/object. Once Java finds it we get the "modifiers" of it, which tell the variable what restrictions/rules it has like final, static, private, public, etc. We find the right variable, and then tell the code that it is accessible which allows us to change these modifiers. Once we have changed the "access" at the root to allow us to manipulate it, we are toggling off the "final" part of it. We then can change the value and set it to whatever we need.
To put it simply, we are modifying the variable to allow us to change its properties, removing the propety for final, and then changing the value since it is no longer final. For more info on this, check out the post where the idea came from.
So step by step we pass in the variable we want to manipulate and...
// Mark the field as public so we can toy with it
field.setAccessible(true);
// Get the Modifiers for the Fields
Field modifiersField = Field.class.getDeclaredField("modifiers");
// Allow us to change the modifiers
modifiersField.setAccessible(true);
// Remove final modifier from field by blanking out the bit that says "FINAL" in the Modifiers
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
// Set new value
field.set(null, newValue);
Combining this all into a new SUPER ANSWER you get.
#RunWith(PowerMockRunner.class)
#PrepareForTest()
class PrivateStaticFinalTest {
#Test
public void testMethod(){
try {
setFinalStatic(PrivateStaticFinal.class.getDeclaredField("variable"), Integer.valueOf(100));
}
catch (SecurityException e) {fail();}
catch (NoSuchFieldException e) {fail();}
catch (Exception e) {fail();}
assertEquals(PrivateStaticFinal.method(), Integer.valueOf(101));
}
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
}
Update
The above solution will work only for those constants which is initialized in static block.When declaring and initializing the constant at the same time, it can happen that the compiler inlines it, at which point any change to the original value is ignored.

ActionScript 3 Override Methods + Increase Visibility

When I extend a class I want to override methods and change their accessibility like a protected method should be public in a certain class. When I compile it says: "Incompatible override". I can't reduce nor can I increase the visibility.
Reducing wouldn't make sense and I don't need it but I was able to increase method visibility in Java. Why not in ActionScript 3 ?
public class OldClass
{
protected function doStuff() : void
{}
}
public class NewClass extends OldClass
{
override public function doStuff() : void
{}
}
Am I doing something wrong ?
No, you're not doing anything wrong. That's just how the language works. From the documentation (emphasis added):
Static methods are not inherited and cannot be overridden. Instance methods, however, are inherited by subclasses and can be overridden as long as the following two criteria are met:
...
The override method must have the same level of access control as the base class method. Methods marked as internal have the same level of access control as methods that have no access control specifier.
The override method must have the same number of parameters as the base class method.
The override method parameters must have the same data type annotations as the parameters in the base class method.
The override method must have the same return type as the base class method.

Accessing protected or private property

In ActionScript 3 is there a way (a hack - maybe through square brackets, maybe through cloning an Object, maybe through prototype, maybe through namespaces, ...) to change a private or protected member of a class?
For example if I have an IconToast class delivered by a someLibrary.swc and I know it has a
protected var windowOptions:WindowOptions;
Can I change it somehow? I've tried many things, for example:
var errorToast:IconToast = new IconToast();
errorToast.addButton("Dismiss");
errorToast.message = "Error when connecting";
errorToast['windowOptions'].timeout = 10 * 1000;
errorToast.show();
(gives me runtime error ReferenceError: Error #1069: Property windowOptions not found on IconToast and there is no default value).
Do this by extending the base class and giving public access to the private/protected method/property etc.
public class MyIconToast extends IconToast
{
public function getWindowOptions():WindowOptions
{
return windowOptions;//here you can access protected (not private though:);
}
}
for private it may not be possible but similar to above solution to some extent it can be done
Best regards
Nope, There is no way to change its modifier directly( That's why it's defined as public, protected and private, right?). The solution of Lukasz 'Severiaan' Grela is OK, but it can be better: use getter/setter to retrieve read/write function.
public function set windowOption(option:int):void;
public function get windowOption():int;
and the private attributes belong ONLY to their class, so if they're packed into SWC, you can't see any of them:D.

conceptual issue in inheritence property of actionscript-3

say, Child class is inheriting Father class and Father class is inheriting spark TextArea class. now from an mxml file (in FLEX4), i am creating multiple objects of Child class. Father class have few static attributes whose values are set by private methods, calling from constructor. Now the question is: all these static attributes are set every time while Child class objects are being created one by one?
If answer is yes then Is it possible that Father class static attributes are set only once and not depends upon the number of Child class objects creation.
Please provide any suggestion or tips
Thanks in advance.
If you are setting static variables from an object's constructor or methods called from the constructor, then yes, they will be set every time. In order to prevent that, just check whether the variable is already set.
public class Foo {
public static var bar:Object;
public Foo(value:Object) {
if (!bar) {
bar = value;
}
}
}
First decide if those static members are really all that important to store as statics because statics are associated with a Class and not an instance it's usually a signal that you're probably doing something you shouldn't if instances are modifying or reading static members. You probably should use a factory method if you need to share that information with the instances. However, if you're sure you should do it then you can use a static initializer block to initialize the members when the class is loaded. Downside is that block throws an exception it can be hard to track down:
public class SomeObject {
private const _someStaticMember : String;
private const _someOtherStaticMember : SomeOtherObject;
static {
_someStaticMember = "foobar";
_someOtherStaticMember = new SomeOtherObject();
}
}

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.