Deciding how to refactor a class having many methods - language-agnostic

I have noticed that my classes tend to be larger/longer compared to code I tend to read online. The code below is intended as an example, but I am more interested in the way to think about and how to approach the problem.
As you will see the class handles many roles and I would love to learn on how to refactor it into other classes and examples, if possible, on practical solutions. Links to books/guides on how to solve this problem would be great.
So I have a Backend class with the following declaration. I am using C#, but I think that my question covers other languages.
public static class Backend {
//These classes are the equivalent classes of a cloud database tables
//Using them to map the tables to objects in my app
public class User{}
public class Place{}
public class SubPriority{}
public class Question{}
public class Parent{}
public class Response{}
public class SubParent{}
//initialize the local and cloud databases
public static async void init();
//Add place to local database
public static string AddPlace(string name, string buildingType)
//Retrieve places from local database
public static List<Place> RetrievePlaces()
//Delete a place from local database
public static bool DeletePlace(string placeID)
public static string AddSubPriority(String name)
public static List<SubPriority> RetrieveSubPriorities()
public static bool DeleteSubPriority(string placeID, int ID)
//Sync local db with cloud
public static async Task<bool> SyncWithCloud()
//Download SubParents from the cloud
public static async Task<List<SubParent>> DownloadSubParents()
//Retrieve SubParents from local
public static List<SubParent> RetrieveSubParents(int parentid)
...
...
...
//Similar methods for parents and questions
//Handling login
public static async Task<bool> Login(string userName, string pass)
static async Task<bool> LoginOnline(string userName, string pass)
static bool LoginOffline(string userName, string pass)
//Check for internet connectivity
static async Task<bool> isConnectedToInternet()
static bool InternetAvailable()
}

Separation of Concerns
The difficulty with keeping all of this logic in one class is that changing one thing is likely to require significant changes to the whole class, which will create bugs. And equally importantly, it's easier to read and understand when classes assume a single role. Code that is readable always has fewer bugs (in my experience).
Your single class is handling at least the following roles:
Maintaining a collection of objects (your "local database")
Reading from/writing to a cloud server
Converting cloud server data to your model class objects
Keeping the local database in sync with the cloud database, in both directions.
Defining your business object models (User, Place, Subpriority etc).
Coordinating all of the above.
If I were implementing this, I'd break 1-4 out into separate classes. For #5, I'd move the models outside of Backend, so they're standalone classes.
Maintaining a collection of objects (your "local database")
Data storage belongs in its own class. With all of your object types, this is already pretty complex.
Reading from/writing to a cloud server
Any code that accesses an external resource belongs in its own class, which does only data access. Ideally this class should be defined first as an interface, and callers should call it only through the interface. This makes it easier to swap providers, and also aids in testing (you can supply a different DAL implementation at runtime for tests) and reinforces separation of concerns.
Converting cloud server data to your model class objects
This can be done in the DAL, or in an intermediate layer. For downloading cloud data, you could add methods to your collection classes like
LocalDatabase.Users.Update(List<User> usersFromCloud){}
Keeping the local database in sync with the cloud database, in both directions.
An intermediate class sitting between Backend, the cloud DAL, and the local database could sync "automatically" whenever it knows the data on one side is stale. Alternatively, this could be moved to a utility class. Which is best depends on your requirements.
Defining your business object models (User, Place, Subpriority etc).
Code outside of the backend is using these models, so they belong outside the backend definition.
Coordinating all of the above.
When you take out everything listed above, what's left will be a bunch of method calls to the new classes to do all the work. Your Backend class will become more of a coordinator that delegates work to the appropriate class.
Other things I'd do differently
Use non-static classes. If you are going to use one global object to provide access to the backend, you can use a singleton. (Google "C# singleton" for examples.). This will make it easier to test your code (by swapping out what you store in the singleton, e.g. with a dummy implementation that returns values from a text file) and easier to switch to a non-global implementation later if that becomes necessary.

Related

How to call a remoteObject method that is outside of my TitleWindow component on Flex?

I have a TitleWindow component. It allows me to save some data provided through 3 TextInput.
That data "fills" a DropDownList which is in another TitleWindow component, not inside the original one.
How can I call the remoteObject method that fills (or refresh) my DropDownList?
Any ideas will be appreciated!
You can simply use a Singleton as a model if you'd like, this will allow you to share data, but beware keep data only that needs to be shared in here or it will just become a global nightmare.
Using a singleton means you'll have a class that you can only ever have one instance of. If you put properties in that class any time you reference it it will be the same memory throughout the application execution.
http://blog.pixelbreaker.com/actionscript-3-0/as30-better-singletons
Marking the singleton class or individual properties as Bindable will make it so you can watch for the changes and call a function.
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_8.html
Putting this together you have something like this:
[Singleton.as]
package
{
[Bindable]
public class Singleton
{
public var myListData:Array;
public static var instance:Singleton;
public static function getInstance():Singleton
{
if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
return instance;
}
public function Singleton( pvt:SingletonEnforcer )
{
// init class
}
}
}
internal class SingletonEnforcer{}
Somewhere else you want to get a handle on this
[MyTitleWindow.as]
var instance:Singleton = Singleton.getInstance();
instance.myListData = [1,2,3];
[MyTitleWindowWithAList]
var instance:Singleton = Singleton.getInstance();
BindingUtils.bindSetter(funcUpdateList, instance, "myListData");
private function funcUpdateList(data:Object)
{
myList.dataProvider = data as Array;
}
Another option is to create an event that carries your data payload, dispatch that event from the first title window, and capture it, the problem with this is you have to register the listeners on the PopUpManager or SystemManager I believe because the TitleWindow's aren't direct children of the Application I believe.
Singletons are a bad idea and you should not get in the habit of using them. Instead, just dispatch an event from the View and catch it from something else that has access to your Service object.
Note that your Service should not be part and parcel of any View--the responsibility of a View is displaying data and capturing requests from the user to change the data, not communicating with a server.
For examples of an application written with this pattern in mind, check out
[Refactoring with Mate] (http://www.developria.com/2010/05/refactoring-with-mate.html) - The example has View source enabled
The same application done with RobotLegs - again, View Source is enabled.
Note that these are written against some popular frameworks, but they are written in such a way that you can easily replace that framework code with something else, even your own code.
For reference, here is the naiive implementation, where the service layer is being called directly in the Views. You couldn't call a different service without changing the Views, though the use of the static service means you could use it from elsewhere.
That static usage survived into the later examples, though today I would never write something depending on a globally accessible object. In part this is because I discovered Test Driven Development, and it is impossible to replace the "real" static object with an object that lets you isolate what you are testing. However, the fact that most of the code in the 2 "better" examples is insulated from that static object means that it is trivial to replace it with one that is provided some other way.
The lesson here is if you're going to use static, global objects, lock them away behind as much abstraction as you can. But avoid them if you're at all interested in best practice. Note that a Singleton is a static global object of the worst kind.

AS3 How do you access an instance of a class from anywhere?

I currently pass a reference to my model through the constructor to any class that needs it in my simple mvc pattern, this can get annoying at times when it starts to go deeper.
How do Classes such as LoadMax allow you from anywhere to simple import the class, and do something like addChild(LoaderMax.getContent("bg"));? Replicating this should surely be a good way to have my model work, without the complexity of big frameworks?
Statics are your friend
As previous answers have noted, TweenLite/Max etc. makes heavy use of static members to get work done. This is exactly like the Math class, for example, and can be a very convenient design pattern. You have global access to the class, and that can definitely alleviate the issue of getting access to variables through deeply nested classes.
Statics are the enemy
Statics, however, bring certain problems to the table. Most importantly, they tend to reduce flexibility and modularity of classes through the often unnecessary addition of tightly coupled relationships. It's a bit like pouring concrete over your application. It does work, but changing behavior becomes difficult as project features change.
Static members != instance members
Note, very clearly, that a static member "belongs" to the class itself, and not an instance of that class. Static members have no access to instance members. This causes troubles when you want to mix these members up in logic. You tend to have to make everything static (the so-called "static-cling" effect). Static patterns are often argued to be argued to be "anti" object-oriented, for precisely this reason. Once you build a structure on a static pattern you tend to lose many of the principles that makes OOD powerful.
In small does, they're pretty nice
That all being said - TweenLite is a great example of a static pattern that is totally appropriate - its a utility package, one that logic is not dependent on. And that should probably be how you leverage statics, too.
To reduce reliance on statics, or even global vars, it does often mean writing more code, but the flexibility in app structure gained is often quite worth it. #Marty_Wallace has a pretty good solution imo.
Demeter and the Paperboy
Finally, I'll just mention the Law of Demeter, or the Principle of Least Knowledge, and the related Paperboy and the Wallet example, which is often pointed to in discussions of statics:
Each unit should have only limited knowledge about other units: only
units "closely" related to the current
unit.
Each unit should only talk to its friends; don't talk to strangers.
Only talk to your immediate friends.
Hopefully that sheds a little bit of light on a fairly complicated and not-often obvious issue.
This is done using the static namespace, however I discourage the use of this.
package
{
public class Main
{
public static function sayHell():void
{
trace("hello!");
}
}
}
You can now call sayHello() like this from anywhere in the application (assuming you've imported the class).
Main.sayHello();
Another thing you can do (to make the entire class accessible from within the application) is create a static property that refers to the class itself:
package
{
public class Something
{
public static var instance:Something;
public function Something()
{
instance = this;
}
public function someFunction():void
{
trace('hello!');
}
}
}
Which you can now use like so:
Something.instance.someFunction();
The only thing to note here is that you need to create an instance of Something for this to work to call the constructor and define instance.
What I would do
Create a base class for all objects in your application
Create a manager class that takes care of these objects
Create a setter within your base class to define the manager
Here's an example:
Base
package
{
public class Base extends Object
{
private var _manager:Manager;
public function set manager(m:Manager):void
{
_manager = m;
init();
}
protected function init():void
{
manager.someFunction();
}
public function get manager():Manager{ return _manager; }
}
}
Manager
package
{
public class Manager extends Object
{
public function someFunction():void
{
trace('hello!');
}
}
}
Now anything that extends Base will have access to anything held in Manager via the manager getter property. All you need to do is make sure you define the manager, which is easily achieved from within anything that extends Base like so:
var something:SomeExtendingClass = new SomeExtendingClass();
something.manager = manager;
The example you gave is just a static method, but to answer your question about a global instance of a class:
package myPackage
{
public var globalVariable:MyClass = new MyClass();
}
You can access it with:
import myPackage.globalVariable;
trace(globalVariable);
I think you have to rethink in which way you want to name your classes.
You can instantiate whatever class you want, at run-time, but to access a instance by name, you have to make changes in your structure. For example, the getContent() function you mentioned in LoaderMax, all it does is to search in an array for the given loader that matchs the name, among other things. You can read the name variable comment for a description.
A name that you use to identify the loader instance. This name can be fed to the getLoader() or getContent() methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".
So in this system, you have to name every single member (loaders in this case) if you want to be able to search them. Because if I call getClassInstance("myinstance"), what is "myinstance" representing? Where should I name it?
That said, if you want to do it for DisplayObjects only, you can use getChildByName. But again, you have to name every DisplayObject (just set the name variable).
Hope this helps.

When should I use/examples of nested classes?

Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...

How do you create your Factories?

So, coming upon the subject of Factories, I'm wondering how they are set up.
From where I stand, I can see 3 types of Factories:
All In One
A factory that basically contains all of the classes used in an application. It feels like it is just having a factory for the sake of having a factory, and doesn't really feel structured.
Example (Where ClassA, Class B, and ClassC have nothing in common except being in the same App):
class Factory
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
Code samples provided are in PHP. However, this question is language-agnostic.
Built-In Factory
The next one is mixing in static functions with the regular functions in order to make special creation patterns (see this question)
Example:
class ClassA
{
public static function buildClass()
public function __construct()
}
Factory On-the-Side
The last one I can think of is having a factory for individual classes, or individual sets of classes. This just seems to variable to be used in an uniform manner.
Example (Where ClassA, B, and C are related, and 1, 2, and 3 are related):
class FactoryAlpha
{
public static function buildClassA()
public static function buildClassB()
public static function buildClassC()
}
class FactoryNumeric
{
public static function buildClass1()
public static function buildClass2()
public static function buildClass3()
}
My question is: Are all of these bad ideas, are any of them bad ideas? Are there other ways of creating factories? Are any of these actually good ideas? What is a good/best way to create Factories.
The point of a factory seems to be to have the code that uses it not need to know which concrete class will be constructed (this should be handled by configuring the factory). That seems to rule out "All-in One" and "Factory-on-the-Side".
I like the approach that Java libraries often use: You have a static method that creates the Factory. The Factory has a getInstance method that creates the instance. This gives you two points of configuration (via system properties): The default FactoryImpl has a number of settings, such as the class it should produce, and if these configuration options are not enough, you can also swap out the FactoryImpl altogether.
As for "All-in One" vs "Factory-on-the-Side", a Factory should not produce unrelated classes I think. Again, it Java terms, every factory produces instances of a certain interface.
"All-in-One" sounds like something that should be replaced with Dependency Injection (where you have a container that produces all kinds of instances and injects them into the application).
If you are really interested in "Preferred technologies", I'd replace them all with Dependency Injection.
If that seems to heavy, just remember that you may not be seeing every use for your factory so don't "New" a hard-coded class in your factory. Instead, have a "Setter" that can specify what class needs to be injected.
This will come in handy later when you are unit testing and need to start injecting mock classes.
But as you make this more general, abstract and reusable, you'll end up back at DI. (Just don't say I didn't warn you)
There's really just two standard sorts of factories, at least according to GOF and the slew of patterns books that followed: The basic Factory, and the Abstract Factory.
A Factory generally returns a concrete instance that the caller refers to through an interface, like so:
// createWidget() here instantiates a BigWidget or SmallWidget or whatever the context calls for
IWidget widget = WidgetFactory.createWidget(someContextValue);
Using a factory with an interface in this way keeps the caller from being coupled into a specific type of the returned object. Following the venerable Single Responsibility Principle, a factory should do one thing, that is, return a concrete instance of the interface that was called for, and nothing more. A basic factory should only have the job of creating one type of object.
An Abstract Factory, on the other hand, can be thought of as a factory of factories, and might be closer to what you were thinking of as an "all in one" factory. An Abstract Factory is usually configured at start-up to return a group of related factories, for instance factories that might create a particular family of GUIs depending on a given context. This is an example of Dependency Inversion that has largely been replaced by using IOC containers like Spring.

Is there a language with object-based access levels?

A common misconception about access level in Java, C#, C++ and PHP is that it applies to objects rather than classes. That is, that (say) an object of class X can't see another X's private members. In fact, of course, access level is class-based and one X object can effortlessly refer to the private members of another.
Does there exist a language with object-based access levels? Are they instead of, or in addition to, class-based access? What impact does this feature have on program design?
Ruby has object-based access level. Here's a citation from Programming Ruby:
The difference between "protected"
and "private" is fairly subtle, and
is different in Ruby than in most
common OO languages. If a method is
protected, it may be called by any
instance of the defining class or its
subclasses. If a method is private, it
may be called only within the context
of the calling object---it is never
possible to access another object's
private methods directly, even if the
object is of the same class as the
caller.
And here's the source: http://whytheluckystiff.net/ruby/pickaxe/html/tut_classes.html#S4
Example difference between Java and Ruby
Java
public class Main {
public static void main(String[] args) {
Main.A a1 = new A();
Main.A a2 = new A();
System.out.println(a1.foo(a2));
}
static class A
{
public String foo(A other_a)
{
return other_a.bar();
}
private String bar()
{
return "bar is private";
}
}
}
// Outputs
// "bar is private"
Ruby
class A
def foo other_a
other_a.bar
end
private
def bar
"bar is private"
end
end
a1 = A.new
a2 = A.new
puts a1.foo(a2)
# outputs something like
# in `foo': private method `bar' called for #<A:0x2ce9f44> (NoMethodError)
The main reason why no language has support for this at the semantic level is that the various needs are too different to find a common denominator that is big enough for such a feature. Data hiding is bad enough as it is, and it gets only worse when you need even more fine grained control.
There would be advantages to such a language, for example, you could mark certain data as private for anyone but the object which created it (passwords would be a great example: Not even code running in the same application could read them).
Unfortunately, this "protection" would be superficial since at the assembler level, the protection wouldn't exist. In order to be efficient, the hardware would need to support it. In this case, probably at the level of a single byte in RAM. That would make such an application extremely secure and painfully slow.
In the real world, you'll find this in the TPM chip on your mainboard and, in a very coarse form, with the MMU tables of the CPU. But that's at a 4K page level, not at a byte level. There are libraries to handle both but that doesn't count as "language support" IMO.
Java has something like this in form of the Security API. You must wrap the code in question in a guardian which asks the current SecuityManager whether access is allowed or not.
In Python, you can achieve something similar with decorators (for methods and functions) or by implementing __setattr__ and __getattr__ for field access.
You could implement this in C# by having some method capable of walking the stack and checking which object the caller is, and throwing an exception if it's not the current class. I don't know why you would want to, but I thought I'd throw it out there.