How to manage combinations of styles: multiple classes, specific classes, or context? - naming-conventions

I'm not much of a web designer or programmer, but I seem to run into this issue with CSS classes: what's the best way of managing sets of CSS classes that share attributes in common?
For example, I'm currently working on an application with a status bar representing the status of a file transfer. It's used in three different locations, each of which is a different size. In addition, if the transfer fails, the bar should be a different color.
What's the best approach, in general:
Add "statusbar" and "transfer-failed" classes to the divs independently, and check for their combined existence?
Have "statusbar" and "statusbar-failed" classes, set the class appropriately, and use careful CSS structuring to avoid repeating code.
Have a "statusbar" class, then use context like the div being inside a "summary" table or a "transfer-failed" div to further specialise it.
Are there any general rules? Approach 3 seems fragile, because changing the name of a seemingly unrelated class could break stuff. Approach 1 feels strange somehow, having classes like "failed" that would be meaningless without another class, and could also mean different things in different contexts (eg, "failed" could also be applied to a failed form validation...) Approach 2 sometimes gets unwieldy, with lots of very specific classes with long names.

If there will always be only one "status bar" feel free to use an
id instead of a class for it.
If there will be multiple on the same page, and they look
anything alike, stick with class.
Assign a transfer-failed class when appropriate. In in your CSS,
under this class, should only have the properties that
differentiates it of the default "status bar". Personally, I like #3
(the context approach). WordPress and other CSMs assign the page
name and category (and anything else you'd like) as <body>
classes. Modernizr uses the <html> tag. More info here: http://perishablepress.com/dynamic-body-class-id-php-wordpress/
#Lokase's SMACSS is great. For more tips on organizing your CSS, check this out: http://coding.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/

Take some time to look at a few CSS methodologies or frameworks, I am a fan of SMACSS
There are a lot examples of best practices out there, you just have to find them and go through the learning curve.

Related

Mess class design

I have a class design that looks like this one:
When Main receives an item, properties of other items can change based on some rules. For example, if Item1 has a red color, item2.level must be 3. Sometimes a value can change properties of multiple items. Implementing all rules in Main class is possible but it's a mess code.
So, I have implemented the Aggregate class that include all items. When Main.setItem(item1) is executed, I update Aggregate with Aggregate.setItem1 and run Rules.updateAggregate that updates items of Aggregate according to all rules.
It works, but Rules class is very inefficient. Because it doesn't know which item has updated, it apply all rules all times. Also, updateAggregate method is very large and difficult to test.
Is there any better design?
To reduce the coupling you could use a design based on events.
Main and Item classes should be publishers of events and Item classes should be also subscribers of event types as they want to react to events.
You should define some event types. For example :
event type : "new Item with ..."
event type : "Item 1 changed the foo property"
and so for...
According to question and comments, here is one example of a design that could work. Gist link to the example code
The example is made using C# but should not have any problems to implement other languages. (Could be easier with dynamic languages)
The design probably doesn’t fit directly to your use case but here are a few points what I try to demonstrate with it and maybe you can find better ideas with this way.
I made a few iterations and this was the first version that I could work on a similar use case without any third party libraries.
Main points of design
In the example, I try to keep Item -classes very clean from rules.
Rules -class is disappeared because, in the example, rules are in Aggregate class. However, I don’t see any problem to implement the same rules in separated Rules class, if needed. I don’t know exactly how complex your rules are and tried to keep the example simple.
The aggregate has methods to raise “notification” about Item changes.
I didn’t test my example but the implementation should be easier to test. For example, you should be put Items on specific state and try how rule behavior works. This can be validated to use unit tests but I didn't have any real use cases.
I tried to kept classes decoupled as possible.
Downsides
Depending on your needs, classes can be too coupled. Specially Aggregate can contain a lot of code so the more decoupled solution should be possible.
Implementation can be varied by programming languages and not always so clean. Originally, I used a similar pattern with event sourcing and modified to this example.
If a number of Items are huge, then the design is not very flexible.
How to improve
As said in comments and other answers, event-based implementation is probably what you want. I used Observer pattern as a starting point but it was going towards event-based implementation.
You should also look at some event-driven libraries that can have a good example of how to implement an application that reacts to changes. Also, those libraries usually help to wire up objects and give more decoupled implementation. Of course, then you are coupled with those libraries but probably not a bad case. No need to reinvent this mechanism anyway.
Check following links that can help with new ideas. Observer vs pub-sub pattern
I completelly agree with #davidxxx that events based design is better approach in your case. You can have a look at the observer design pattern. In case your business logic is so complex that you are not able to provide reqired parameters , you can always inject the whole list/tree/whatever of items and perform find operations on it.

Tips on how to balance Polymorphism/Inheritance/TypeData architecture with Prototype/Flyweight pattern in a complex card game?

I am trying to develop a card game with Kotlin, but I feel like the complex architecture decisions I feel I have to make are stalling my process.
I would like to create a solid and flexible foundation for potentially dozens of different cards with different effects, of different types (e.g. spell, vehicle, weapon...).
Intuitively I feel like giving each different Card its own subclass would be ridiculous for several reasons, such as the loss of flexibility (can't (without crazy hacks) create new kinds of cards dynamically) and escalating complexity.
On the other hand, there will be different categories of cards (types) which generally have more in common with each other than cards - so it feels like I should definitely subclass Card because otherwise I would end up with Type enums (SPELL, WEAPON, VEHICLE...) and ugly switch-statements replacing what's usually dealt with by inheritance and polymorphism.
I initially had problems conceiving how to access specific behaviors of subclasses who live in collections of superclasses, but I now understand how I can solve this using the visitor pattern - all fine so far.
My problem now is this architectural approach seems to conflict with other things I have planned and which I consider necessary or at least very worthwhile to have:
Hybrid of Prototype-Flyweight-Pattern:
I have created a 'cyclopedia' of prototype cards that can be copied. Cards consist of a shared static part and a unique dynamic part:
Naturally, I would like to create subinstances of the identifying components in the following manner:
Doing this doesn't seem to be possible in a satisfying way no matter how I approach it. There are many solutions but all seem like weak compromises to me:
Doing it the way I described it means subclasses have to save
multiple references to their components; a baseclass and one subclass
one for each. It also leads to an ugly situation where type
attributes are spread over several component-classes all dependent on
each other.
Using interfaces instead of inheritance leads to loads of code duplication.
Subclassing only the components but not card itself hides type information in the innards of cards and also demands ugly reflection
for accessing subclass traits.
Implementing a data-equivalent of type-information instead of subclassing to circumvent the limiting rules of Kotlin inheritance
hierarchies seems to be hacky and removes IDE support.
I am sure there are even more approaches I have considered over the course of the last two weeks, but these are all I can remember right now.
I know that you probably would require more complete information on what I am planning to do to give me concrete answers, but since it's too complex and I don't know all about where this is going either, I am satisfied with rough ideas in the sense of 'consider this' or 'whatever you are doing, stay away from this' or general advice about how to deal with such a 'design crysis' where things seem so complex you don't know how to start.
Of course I am ready to elaborate or detail parts of my description if it becomes necessary.
Just thinking here.
What about creating a BaseCard class with Card low-level common parts, then a class for each category that inherits from BaseCard, named like Category, where you store each category common parts, and then classes CardofSomeType inheriting from its respective Category. So in a CardofSomeType you inherit anything relevant from either class, and you just add new Card(s)ofSomeType(s) to extend your set.
About what data is instance specific or shared in the class, that's orthogonal to this and an implementation detail of each class.

PROS and CONS on using one classPageObject for storing all xpath/css selectors and etc., using Java

What are the PROS and CONS on using onePageObject class for storing my all xpath/css selectors and etc., and then use them in other page object methods.
I'm thinking how lower the needless xpath's that are constantly is repeating in different pageObjects class.
Any suggestions?
Somebody already doing this? If yes, is it easyer or harder to find what you need?
I'm thinking to use the code something like this:
ObjectClass.java
Public class ObjectClass myXpaths {
#FindBy(xPath);
private button xPathButtonAdd;
#FindBy(xPath);
private button xPathButtonDelete;
#FindBy(xPath);
private button xPathButtonCancel;
}
ObjectClass2.java
import ObjectClass;
Public class void ObjectClass2 myPageObject {
ObjectClass smth = new ObjectClass();
smth.xPathButtonAdd.click();
smth.xPathButtonDelete.click();
smth.xPathButtonCancel.click();
}
CONS as I see it:
One huge class of selectors - huge classes are typical code smell.
Other page object class would inherit from or initialize an object
with a lot of selectors it doesn't need.
Violation of Single Responsibility Principle (SRP).
PROS:
Avoiding some repetitive code - you could avoid it by other means
(see example bellow)
....
If the reason why you think of doing this is minimizing repetitive code, you should rather think of how to extract that repetitive code to separate classes. For instance, given a application with multiple pages where every page has standart search section, you can extract it to separate class SearchSection or SearchBox and use it in pages where you need it.
If you gave an example of repetitive code or what do you want to do, it would be easier to suggest something.
Ok, I think I get now where you want to go. I would definitely recommend separating the selectors from the actual code. We organize our page objects in classes that more or less represent one screen of the application under test. Those classes are then again in a structure of packages representing the business process that is tested. That way we can easily reuse page elements and if something in the application under test changes we only have to touch this "repository" of page elements but not the script that does the action. We also use prefixes like "link", "button", "input" and so on that indicate the type of page element so that the action code is easier to understand and read.
But I would really advise against throwing all in one huge class, because you might have trouble finding things later on. :-)

How do you define a Single Responsibility?

I know about "class having a single reason to change". Now, what is that exactly? Are there some smells/signs that could tell that class does not have a single responsibility? Or could the real answer hide in YAGNI and only refactor to a single responsibility the first time your class changes?
The Single Responsibility Principle
There are many obvious cases, e.g. CoffeeAndSoupFactory. Coffee and soup in the same appliance can lead to quite distasteful results. In this example, the appliance might be broken into a HotWaterGenerator and some kind of Stirrer. Then a new CoffeeFactory and SoupFactory can be built from those components and any accidental mixing can be avoided.
Among the more subtle cases, the tension between data access objects (DAOs) and data transfer objects (DTOs) is very common. DAOs talk to the database, DTOs are serializable for transfer between processes and machines. Usually DAOs need a reference to your database framework, therefore they are unusable on your rich clients which neither have the database drivers installed nor have the necessary privileges to access the DB.
Code Smells
The methods in a class start to be grouped by areas of functionality ("these are the Coffee methods and these are the Soup methods").
Implementing many interfaces.
Write a brief, but accurate description of what the class does.
If the description contains the word "and" then it needs to be split.
Well, this principle is to be used with some salt... to avoid class explosion.
A single responsibility does not translate to single method classes. It means a single reason for existence... a service that the object provides for its clients.
A nice way to stay on the road... Use the object as person metaphor... If the object were a person, who would I ask to do this? Assign that responsibility to the corresponding class. However you wouldn't ask the same person to do your manage files, compute salaries, issue paychecks, and verify financial records... Why would you want a single object to do all these? (it's okay if a class takes on multiple responsibilities as long as they are all related and coherent.)
If you employ a CRC card, it's a nice subtle guideline. If you're having trouble getting all the responsibilities of that object on a CRC card, it's probably doing too much... a max of 7 would do as a good marker.
Another code smell from the refactoring book would be HUGE classes. Shotgun surgery would be another... making a change to one area in a class causes bugs in unrelated areas of the same class...
Finding that you are making changes to the same class for unrelated bug-fixes again and again is another indication that the class is doing too much.
A simple and practical method to check single responsibility (not only classes but also method of classes) is the name choice. When you design a class, if you easily find a name for the class that specify exactly what it defines, you're in the right way.
A difficulty to choose a name is near always a symptom of bad design.
the methods in your class should be cohesive...they should work together and make use of the same data structures internally. If you find you have too many methods that don't seem entirely well related, or seem to operate on different things, then quite likely you don't have a good single responsibility.
Often it's hard to initially find responsibilities, and sometimes you need to use the class in several different contexts and then refactor the class into two classes as you start to see the distinctions. Sometimes you find that it's because you are mixing an abstract and concrete concept together. They tend to be harder to see, and, again, use in different contexts will help clarify.
The obvious sign is when your class ends up looking like a Big Ball of Mud, which is really the opposite of SRP (single responsibility principle).
Basically, all the object's services should be focused on carrying out a single responsibility, meaning every time your class changes and adds a service which does not respect that, you know you're "deviating" from the "right" path ;)
The cause is usually due to some quick fixes hastily added to the class to repair some defects. So the reason why you are changing the class is usually the best criteria to detect if you are about to break the SRP.
Martin's Agile Principles, Patterns, and Practices in C# helped me a lot to grasp SRP. He defines SRP as:
A class should have only one reason to change.
So what is driving change?
Martin's answer is:
[...] each responsibility is an axis of change. (p. 116)
and further:
In the context of the SRP, we define a responsibility to be a reason for change. If you can think of more than one motive for changing a class, that class has more than one responsibility (p. 117)
In fact SRP is encapsulating change. If change happens, it should just have a local impact.
Where is YAGNI?
YAGNI can be nicely combined with SRP: When you apply YAGNI, you wait until some change is actually happening. If this happens you should be able to clearly see the responsibilities which are inferred from the reason(s) for change.
This also means that responsibilities can evolve with each new requirement and change. Thinking further SRP and YAGNI will provide you the means to think in flexible designs and architectures.
Perhaps a little more technical than other smells:
If you find you need several "friend" classes or functions, that's usually a good smell of bad SRP - because the required functionality is not actually exposed publically by your class.
If you end up with an excessively "deep" hierarchy (a long list of derived classes until you get to leaf classes) or "broad" hierarchy (many, many classes derived shallowly from a single parent class). It's usually a sign that the parent class does either too much or too little. Doing nothing is the limit of that, and yes, I have seen that in practice, with an "empty" parent class definition just to group together a bunch of unrelated classes in a single hierarchy.
I also find that refactoring to single responsibility is hard. By the time you finally get around to it, the different responsibilities of the class will have become entwined in the client code making it hard to factor one thing out without breaking the other thing. I'd rather err on the side of "too little" than "too much" myself.
Here are some things that help me figure out if my class is violating SRP:
Fill out the XML doc comments on a class. If you use words like if, and, but, except, when, etc., your classes probably is doing too much.
If your class is a domain service, it should have a verb in the name. Many times you have classes like "OrderService", which should probably be broken up into "GetOrderService", "SaveOrderService", "SubmitOrderService", etc.
If you end up with MethodA that uses MemberA and MethodB that uses MemberB and it is not part of some concurrency or versioning scheme, you might be violating SRP.
If you notice that you have a class that just delegates calls to a lot of other classes, you might be stuck in proxy class hell. This is especially true if you end up instantiating the proxy class everywhere when you could just use the specific classes directly. I have seen a lot of this. Think ProgramNameBL and ProgramNameDAL classes as a substitute for using a Repository pattern.
I've also been trying to get my head around the SOLID principles of OOD, specifically the single responsibility principle, aka SRP (as a side note the podcast with Jeff Atwood, Joel Spolsky and "Uncle Bob" is worth a listen). The big question for me is: What problems is SOLID trying to address?
OOP is all about modeling. The main purpose of modeling is to present a problem in a way that allows us to understand it and solve it. Modeling forces us to focus on the important details. At the same time we can use encapsulation to hide the "unimportant" details so that we only have to deal with them when absolutely necessary.
I guess you should ask yourself: What problem is your class trying to solve? Has the important information you need to solve this problem risen to the surface? Are the unimportant details tucked away so that you only have to think about them when absolutely necessary?
Thinking about these things results in programs that are easier to understand, maintain and extend. I think this is at the heart of OOD and the SOLID principles, including SRP.
Another rule of thumb I'd like to throw in is the following:
If you feel the need to either write some sort of cartesian product of cases in your test cases, or if you want to mock certain private methods of the class, Single Responsibility is violated.
I recently had this in the following way:
I had a cetain abstract syntax tree of a coroutine which will be generated into C later. For now, think of the nodes as Sequence, Iteration and Action. Sequence chains two coroutines, Iteration repeats a coroutine until a userdefined condition is true and Action performs a certain userdefined action. Furthermore, it is possible to annotate Actions and Iterations with codeblocks, which define the actions and conditions to evaluate as the coroutine walks ahead.
It was necessary to apply a certain transformation to all of these code blocks (for those interested: I needed to replace the conceptual user variables with actual implementation variables in order to prevent variable clashes. Those who know lisp macros can think of gensym in action :) ). Thus, the simplest thing that would work was a visitor which knows the operation internally and just calls them on the annotated code block of the Action and Iteration on visit and traverses all the syntax tree nodes. However, in this case, I'd have had to duplicate the assertion "transformation is applied" in my testcode for the visitAction-Method and the visitIteration-Method. In other words, I had to check the product test cases of the responsibilities Traversion (== {traverse iteration, traverse action, traverse sequence}) x Transformation (well, codeblock transformed, which blew up into iteration transformed and action transformed). Thus, I was tempted to use powermock to remove the transformation-Method and replace it with some 'return "I was transformed!";'-Stub.
However, according to the rule of thumb, I split the class into a class TreeModifier which contains a NodeModifier-instance, which provides methods modifyIteration, modifySequence, modifyCodeblock and so on. Thus, I could easily test the responsibility of traversing, calling the NodeModifier and reconstructing the tree and test the actual modification of the code blocks separately, thus removing the need for the product tests, because the responsibilities were separated now (into traversing and reconstructing and the concrete modification).
It also is interesting to notice that later on, I could heavily reuse the TreeModifier in various other transformations. :)
If you're finding troubles extending the functionality of the class without being afraid that you might end up breaking something else, or you cannot use class without modifying tons of its options which modify its behavior smells like your class doing too much.
Once I was working with the legacy class which had method "ZipAndClean", which was obviously zipping and cleaning specified folder...

How to prevent multiple classes for the same business object?

A lot of the time I will have a Business object that has a property for a user index or a set of indexes for some data. When I display this object in a form or some other view I need the users full name or some of the other properties of the data. Usually I create another class myObjectView or something similar. What is the best way to handle this case?
To further clarify:
If I had a class an issue tracker and my class for an issue has IxCreatedByUser as a property and a collection of IxAttachment values (indexes for attachment records). When I display this on a web page I want to show John Doe instead of the IxCreatedByUser and I want to show a link to the Attachment and the file name on the page. So usually I create a new class with a Collection of Attachment objects and a CreatedByUserFullName property or something of that nature. It just feels wrong creating this second class to display data on a page. Perhaps I am wrong?
The façade pattern.
I think your approach, creating a façade pattern to abstract the complexities with multiple datasources is often appropriate, and will make your code easy to understand.
Care should be taken to create too many layers of abstractions, because the level of indirection will ruin the initial attempt at making the code easier to read. Especially, if you feel you just write classes to match what you've done in other places. For intance if you have a myLoanView, doesn't necessarily you need to create a myView for every single dialogue in the system. Take 10-steps back from the code, and maybe make a façade which is a reusable and intuitive abstraction, you can use in several places.
Feel free to elaborate on the exact nature of your challenge.
One key principle is that each of your classes should have a defined purpose. If the purpose of your "Business object" class is to expose relevant data related to the business object, it may be entirely reasonable to create a property on the class that delegates the request for the lookup description to the related class that is responsible for that information. Any formatting that is specific to your class would be done in the property.
Here's some guidelines to help you with deciding how to handle this (pretty common, IMO) pattern:
If you all you need is a quickie link to a lookup table that does not change often (e.g. a table of addresses that links to a table of states and/or countries), you can keep a lazy-loaded, static copy of the lookup table.
If you have a really big class that would take a lot of joins or subqueries to load just for display purposes, you probably want to make a "view" or "info" class for display purposes like you've described above. Just make sure the XInfo class (for displaying) loads significantly faster than the X class (for editing). This is a situation where using a view on the database side may be a very good idea.