How should I treat variables that aren't necessarily class properties but are used by several methods? - oop

I occasionally find myself with several methods in a class that all require the same data (for example, a query object). Typically, there will be one public method with a generic name like parseReport() which in turn delegates work out to several private methods and finally returns the finished product:
public function parseReport( queryObject ) {
queryObject = correctDatesAndTimes( queryObject );
queryObject = sortByCusomter( queryObject );
queryObject = buildHierarchy( queryObject );
return queryObject;
}
private function correctDatesAndTimes( queryObject ) {
// do some stuff
return queryObject;
}
private function sortByCusomter( queryObject ) {
// do some stuff
return queryObject;
}
private function buildHierarchy( queryObject ) {
// do some stuff
return queryObject;
}
So my question is, should my queryObject be a class-level property that all of my methods will reference rather than passing it through as an argument to the method each time it is called?

In a case like this, queryObject should not be a class property. If you look at it, you actually have one big function that is split in several smaller functions. If it was one big function, you wouldn't make a class property of it.
Data belongs in a class property, when the data is actually a part of the class. Remember that
a class definition is the encapsulating of both data and behavior.

In your example you need to pass the query object as a parameter, as it will be changed inside the private function.
Additionally putting it into a private property will give you headaches if you go multithreaded.

Related

Execute a method when object is changed (OOP)

I'm learning OOP and trying to write a simple program that will execute some method every time when a specific varible will change.
I have two classes:
public class SomeClass {
private OtherClass object;
public OtherClass getObject() {
return this.object;
}
public void setObject(OtherClass object) {
objectChanged();
this.object = object;
}
private void objectChanged() {
System.out.println("Object has changed");
}
}
public class OtherClass {
private int value = 5;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
The variable objectChanged should be called every time when variable "object" is changed. My first naive idea was to put the method call inside of set function. But what if you change the object after you set it? Like this:
SomeClass someObject = new SomeClass();
OtherClass otherObject = new OtherClass();
someObject.setObject(otherObject); //"Object has changed"
otherObject.setValue(10); //nothing happens yet
I need someObject to realize that object stored inside of it changed its value to 10, but how do i do it? Is it even possible in OOP?
It looks to be reasonable, but one should consider many things. This is why there is no automatic way to do it in general. It is not part of the OOP paradigm as such. If this would be some automatic behavior, it would cause huge overhead as it is not often needed to observe changes this way. But you can, of course, implement your way depending on your concrete requirements.
There are at least two approaches.
In MVVM (like WPF) there is an INotifyPropertyChanged interface (let's call it a pattern) you can use to trigger a notification yourself, mutch like you did with SomeClass. However when you are nesting objects, you need to wire up that mechanism.to cascade: you should do the same with OtherClass and also connect the actual instances to bubble up changes.
See: https://rehansaeed.com/tag/design-patterns/
An other option is the Observable pattern. Each time the object changes state, you emit an instance - the current instance. However, you should care to emit unmutable objects. At least by using an interface that makes it read-only. But you still need to wire up the object tree to react to the changes of nested objects.
If your platform supports reflection, and you create a proper toolset, you could make this wiring up quite simple. But again: this is not strictly related to the paradigm.

Kotlin: data class private setter public getter

Is there any way I can make a private setter and a public getter in a Kotlin Data Class?
data class Test(var attribute: String) {
// attribute can be mutated inside this class
// but outside only readable ?
}
A simple approach would be to have a private var, but then to provide a public property that delegates to it:
data class Test (private var attribute_ : String) {
val attribute: String get() = attribute_
}
To add some background to the other answer:
There's no way to do this directly in the constructor, though there have been several proposals as to how it could be added to the language; see here.
If it weren't a data class, I'd suggest this alternative:
class Test(_attribute: String) {
var attribute = _attribute
private set
}
That only stores one value in the object, so is marginally more efficient.
But since this is a data class, that's not possible.  (Data classes can't have non-properties in their primary constructors.)  So the other answer's suggestion seems best.

Suppressing Method Return in Object Oriented Language

I'm going to preface this by saying that this is by no means a major issue, more of something I haven't really heard talked about in terms of programming language design, and I was wondering if anyone had any interesting solutions.
The crux of the problem is this. Sometimes in an object-oriented language, I want to be able to modify an object via one of its methods, but return the object itself instead of what that method returns.
to give a java example:
class MyClass{
public MyClass(List<Integer> list){
//do constructor stuff
}
public MyClass(Integer i){
//what I would like to be able to do
this((new LinkedList<Integer>).add(i));
}
}
I can't create a temporary list in the second constructor, because this() must be the first line. Obviously there are a lot of ways to do this by changing the implementation, like creating an add() method that returns the object, making it the responsibility of the function constructing the object to make the list, etc.
But, considering a lot of the time you can't/don't want to modify or create a subclass (for LinkedList) and you might not want to muddy up the calling code, being able to modify and return an object in the style of ++x could be really useful. Something like
this(#(new LinkedList).add(i) to signify you want to object, not the method return. Does anyone know of a language that allows this is some concise syntactic way? If not, would this be useful at all or am I missing something fundamental here?
Wouldn't this work?
public class MyClass{
public MyClass(List<Integer> list){
//do constructor stuff
}
public static MyClass create(Integer i) {
List<Integer> list = new new LinkedList<Integer>();
list.add(i);
MyClass myClass = new MyClass(list);
return myClass;
}
}
This is somewhat common design pattern called Factory Pattern.
I think the cleanest way to solve this is to have an initialize method called from the constructors.
class MyClass
{
public MyClass(List list){
init(list);
}
public MyClass(Integer i){
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(i);
init(list);
}
protected init(List<Integer> list)
{
// do init stuff here
}
}

Velocity Eventhandler

in velocity, when you do $object.variable if it not be able to find the getter function to
access it or the getter returns a null. it will just show $object.variable explicitly on the page
I know there is a quiet reference, but I don't want to add ! sign to thousands of variables.
I have tried InvalidReferenceEventHandler, NullValueHandler they all didn't get called.
I wander is there a specific type of Eventhandler for this.
Many thanks
The above seems to be a valid choice as well. However here is another option:
public class AppSpecificInvalidReferenceEventHandler implements
InvalidReferenceEventHandler
{
private static final Logger LOGGER =
Logger.getLogger(AppSpecificInvalidReferenceEventHandler.class);
#Override
public Object invalidGetMethod(Context context, String reference,
Object object, String property, Info info)
{
reportInvalidReference(reference, info);
return "";
}
#Override
public boolean invalidSetMethod(Context context, String leftreference,
String rightreference, Info info)
{
reportInvalidReference(leftreference, info);
return false;
}
#Override
public Object invalidMethod(Context context, String reference, Object object,
String method, Info info)
{
if (reference == null) {
reportInvalidReference(object.getClass().getName() + "." + method, info);
} else {
reportInvalidReference(reference, info);
}
return "";
}
private void reportInvalidReference(String reference, Info info)
{
LOGGER.info("REFRERENCE: " + reference + " Info <" + info + ">");
}
}
You'll also need to add the following to your velocity.properties file:
eventhandler.invalidreferences.class=path.to.package.AppSpecificInvalidReferenceEventHandler,org.apache.velocity.app.event.implement.ReportInvalidReferences
You might be surprised at the results though, so it will likely need fine-tuning dependent upon your needs.
I'm basing this off of Engine-1.7 code.
It seems that when an invalid method is called that the utility method EventHandlerUtil.invalidGetMethod is called. This method creates a new InvalidGetMethodExecutor (this is an inner class on InvalidReferenceEventHandler). Eventually this chains down into a call to invalidReferenceHandlerCall which eventually iterates over any handlerIterators which have been defined. Unfortunately I don't know enough about the internals of Velocity to tell you how to inject these values though. My guess is that the user list will suggest a way to override this behavior or a suggestion will be to use / implement a custom tool.
Edit:
According to the Developer Guide you can do the following. You'll need to write some code to deal with it, but it shouldn't be too difficult:
Pluggable Introspection
runtime.introspector.uberspect = org.apache.velocity.util.introspection.UberspectImpl
This property sets the 'Uberspector', the introspection package that handles all introspection strategies for Velocity. You can specify a comma-separated list of Uberspector classes, in which case all Uberspectors are chained. The default chaining behaviour is to return the first non-null value for each introspection call among all provided uberspectors. You can modify this behaviour (for instance to restrict access to some methods) by subclassing org.apache.velocity.util.introspection.AbstractChainableUberspector (or implementing directly org.apache.velocity.util.introspection.ChainableUberspector). This allows you to create more interesting rules or patterns for Uberspection, rather than just returning the first non-null value.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.