Breaking up a large "monolithic" class into smaller ones [closed] - oop

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
What is the best way to go about breaking up a large "monolithic" class into smaller ones?
I have designed a simple chat system that has User objects and Channel objects, where a user can be in and talk in a number of channels.
Here is a diagram of my design:
The primary issue I have with this design is that the ChatManager class is a bit monolithic, i.e. it does too many things. In a previous incarnation it also handled channel membership, which has now been separated out in to ChannelMembershipManager.
What is the best way to go about "simplifying" my ChatManager class? Are there any other problems with my design I am not seeing?

The best way to break up that monolithic manager is to assign responsibilities to the classes, according to OO tenets. Here are some suggestions that immediately come to mind. Don't expect perfection, this is just off the top of my head.
I see no need for a "Manager" class, although I do see a need to track all the instances of the Channel class and all the instances of the User class. Maybe this could be done with class statics within each class. (These indexes could be modeled in UML using qualifiers, which work kind of like hash maps. The Channels and Users really don't even need numbers! Those numbers are merely one of many ways to code this.
Each instance of the User class can use a command channel to communicate with a person. When a person asks the instance of the User class to join a channel, it can create an instance of a Private Channel that manages a per-channel socket that is private to one person, then ask an instance of the requested Channel for permission to accept it. That Private Channel could have methods to poll(), read() and write().
An instance of a Channel class chould be responsible for announcing things when a User joins or leaves. Each instance of a Channel class should be responsible for polling the connected Private Channel instances, reading messages / commands, and taking action, such as repeating a message out to all the other Private Channels.
This is just off the top of my head. If I took some time to think about it, I might see some potential problems or optimizations I could make, but hopefully this gives you some ideas for how to split up a "manager" monolith according to OO tenets.

Related

Best practices for discarding no longer needed objects in memory managed languages [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Lets say we have a top level object, in a game for example that represents some physical thing in the game world. The top level object then owns several sub-objects, like a bounding box, graphical object, ect. By own I mean that when it dies so should it's sub-objects.
Lets also say there is a graphical manager object that keeps track of all existing graphical objects in order to draw them or something.
Now lets say that top level object leaves the game world, it's destroyed or we load another level, whatever. We can at this point remove it's reference and it will be GCed, however the graphical object it owns still has a reference to it in the graphical manager. So there needs to be some mechanism of informing the graphical manager to remove it's reference to the graphical object. It's this mechanism that I'm asking about.
The best way I can think of is that every object needs a public alive Boolean flag and any other object that doesn't own it but interacts with it and may need to keep a reference to it then needs logic to check for that flag and remove it's references if it's false. But this to me seems like a fairly inelegant solution.
You idea is not only inelegant; it is also the not good OOP. The last thing you want to do is to expose a field of a class; and have outside classes depend on the content of that field.
That is a direct violation of the Tell Don't Ask principle. State should be internal; you do not expose - especially not for the purpose of other objects making decisions based on this state. And of course: most languages do not allow you to synchronize on a field - meaning that this approach scream race conditions all over the place (when different threads are reading/writing to that field). You can mitigate this by making the field volatile (if your language allows for that).
One alternative approach would be to look into the observer pattern. Meaning: the graphical manager registers itself as listener; for example on a central "game manager" - that one component that is actually responsible for adding/removing your game objects. And each time the game manager adds/removes an object, the graphical manager gets notified and can adapt its data structures.

Why is public/private such an important programming aspect? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Why do in most programming languages do you get the ability to have private and or public methods/functions classes and properties?
Does it make much of a difrence to let's say.. have all classes, methods and properties be public?
I know that if you have all your methods, classe ans properties set to private nothing will work.
So at least I know that much.
But does the distinction between the two matter? What's the big deal if one class knows another Class "that is meant to be private" exists?
When you make something public, you enter a contract with the user class: "Hey, this is, what I offer, use it or not." Changing the public interface is expensive, because you have to change all code using that public interface, too. Think of a developer of a framework like Cocoa used by thousands of developers. If you change one public methods, for example removing one, thousands of apps break. They have to be changed, too.
So making everything public simply means that you cannot change anything anymore. (You can, but the people will get angry at one point.)
Let's think of having a class implementing a list. There is a method to sort it: sortListWithKey. You make that public because you want the users of the class to get a sorted list. This is good.
There are several algorithms for sorting. Let's say, you implement one that needs to calculate the meridian (the middle element). You need this method internally for your sorting algorithm. So it is enough, to implement it privately. Changing the whole structure of data holding including the implemented sorting algorithm is no problem and will not break existing code using that class.
But if you made the meridian method public (remember: you implemented it, because you needed it internally), you still have to keep it, even the new sorting algorithm does not need it. You cannot remove it anymore, even with the new structure it is very hard (and/or expensive) to keep the method.
So make that part of your implementation public that is useful for the users, but no more. Otherwise you shackle yourself.
If humans had perfect memory, documentation and communication skills, and made no mistakes, then there might not be a useful difference. But using or changing something from the wrong file and then forgetting about it (or not documenting it clearly for the rest of the team, or yourself in the future) is too common a cause of hard-to-find bugs.
Marking things private makes it a bit more work to create the same types of bugs, and thus less likely that lazy/sleepy programmers will do all that extra work just to mess up the application.
In computer science it is called information hiding. You, as a programmer, want to offer only necessary methods or properties to other programmers which will use your public API and this is the way how you can achieve so-called low coupling between modules.

What is the advantage to using an event-driven approach vs procedural programming? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What are the pros and cons of using an event-driven approach vs a non-event-driven (procedural) approach?
Without EDP:
Object A responds to some user input. Object A calls a method in Object B and a method in Object C and they perform their respective tasks.
With EDP:
Object A responds to some user input. Object A publishes an event in which Objects B and C are subscribed. Relevant data is packaged up into an EventArgs and received by B & C and they perform their respective tasks.
Is there an advantage to using one or the other? I'm at a crossroads where I need to choose. However, I do not have any objective information on which one is superior, and in what ways one may have an advantage over the other.
Thanks!
Edit: I am understanding the difference in a similar fashion to how it's described here: https://stackoverflow.com/a/28135353/3547347
Is there an advantage to using one or the other?
Yes - using events decouples A, B, and C. Without events, you cannot, for example, extend functionality by having another type respond to As events without modifying As code.
The downside is that it's harder to code (though not terribly) and you have to code more "plumbing" to add all of the relevent events. It also makes it harder to trace logic since you don't know what may be listening to As events at any one time.
Extendability and maintenance. Instead of having to go back to the method and adding to it every time you want to add a new 'subscriber' in your without EDP example, you'll just add the method you want to call to its list of subscribers.
OOP is all about encapsulating the parts of your code that change, so that changing them has as few consequences as possible. You don't want to have to modify a vaguely related class each time you need new functionality elsewhere in a project.
So I would say given the two options, always go with the event driven model.
I think you are talking about an observer pattern.
You use the observer pattern when you don't have an Object B and Object C at the time you are implementing Object A; or if you know that later, additional classes will need to know about the event, but you do not want them to have to modify the code for Object A.
Event-driven programming is a concurrency model for handling IO bound process (like user input in your example). So, really, both processes you've described are event-driven.
The difference between the two examples is that by introducing the publish / subscribe abstraction between the "observer" object and the "responder" objects you are, as D Stanley mentions, decoupling the two layers by adding a layer of indirection.
The advantage of this approach is greater abstraction (at the expense of just a little more complexity). So you could do things like put a queue between the "observers" and the "responders" which can allow you to control and observe your process, and scale your system.
So, for example, Your "observer" could be a front-end application that queues jobs on to a queue server that is queried by the "responders" which are other applications that run on other servers. That would be one way to architect a multi-tier application.

What are the pros and cons of creating a new class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is a probably a very basic question, but it's one I'm actually running into as I'm learning more about Actionscript 3 in particular. However, my first question is very general: When is appropriate to put functionality in a new class rather than a new function in the same class? According to this Java tutorial, which focuses on basic object-oriented principles, a class is supposed to be a "blueprint of an object". I always understood this to mean that any functionality or behavior that the object would use should be contained within the class. However, according to the single responsibility principle, each class should have only one reason to change. For example, you should have one class to compile a report and one class to print it rather than a single Report class.
Can you guys help me understand the pros and cons to creating a new class? What are the costs to splitting an object into multiple classes? Are there compile-time or performance costs for keeping related functionality in the same class, or for splitting it into two? Are there perhaps times that you would want to split things out, while you might want to keep them together other times?
As far as I remember, there isn't a big difference between having 1 class which can do everything or several classes which can do the same.
It's about readability and how you can extend the code. It's also just about clean code and coupling.
If you have a class called "Printer" you don't want to have "WaterCoolerSound()" in it. Of course the more objects you have the higher the chance is that you can run out of memory. But I am not entirely sure whether one object with all functionality or several classes with the same functionality spread out, takes more memory.
In fact, you could say that if you JUST need a little bag to hold on to some data and not be able to dance like a bear at the same time, it would make sense to have two separate classes.
It's advisable not to think about the performance before you have the code. From the maintainability and understandability viewpoint, of course, smaller classes, with smaller methods are superior. (see The Single Responsibility Principle again :)
Don't get so confused about making classes for just a function. A class should have only related functions.If the functions are of different kinds which will do totally different functionalities and use totally different kind of variables then only u should make a separate class.

Is good to return a generic object with all important returning values from a facade signature? [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 6 years ago.
Improve this question
Since I asked How has to be written the signature in facade pattern? question, I've thought about how to create a signature for an API that has to be both useful and efficient (and a aesthetically nice solution!) . I've seen some APIs and their boundary interfaces at the top expose the following style of signature:
public List<InterestingDTO>
ANecessaryMethodToCompleteABusinessProcess(int aParameter,
InterestingDTO aSecondParamenter)
In this style, business rules violations and other normal/abnormal business situations had to be reported using an specific exception designed for this signature or adopting some convention like returning nulls to state the situation at the end of method's execution.
I think that to use exceptions to show business problems can lead to maintainability problems and it surely is a bad practice (there is a bunch of technical bibliography arguing about this). So, to cope with this problems I suggest to use an structure or a class like this:
public class ReturnValue<T>
{
public T returnedValue;
public string message;
public Status status;
}
enum Status {SUCCESS, FAILURE, ANY_OTHER_STATUS};
the former signature can then be written like:
public ReturnValue<List<InterestingDTO>>
ANecessaryMethodToCompleteABusinessProcess(int aParameter,
InterestingDTO aSecondParamenter)
Where all interesting things for any consuming layers can be known, at least, efficiently. Notice that there are not exceptions to control flow (except probably for those you want outer layers to know), and business layer can have the entire control about business error messages. Do you think this approach has any flaw?
Please, if possible, add some bibliography for your answer.
We pretty much use the same throughout our enterprise apps, with two additions, viz 1) for transactional services, an additional List<> property containing a list of "Validation Results", each of which models a single business rule or validation rule violation, which can then be reported back to the client (user or service consumer) with as much context information as possible, and 2) for data services we add paging information, indicating how much total data is available to the client (given that we only allow a finite number of rows to be returned). This allows the client to tie into a pagination strategy.
The only complaint thus far is for Service Consumers - when we exposed service methods returning the typed generic across the enterprise (ESB / SOA), is that the WSDL / naming of the generics can be cumbersome (e.g. ReturnResultOfPOUpdateRequestJQ3KogUE). This isn't of much concern to .NET clients if we share the Entities on both client and service, but for other clients such as Java, Mobile etc can be problematic, and sometimes we need to provide an alternative facade for such clients without the generics.