In my application, there are several components which will generate various different types of application-specific events. These events will be published out to a broker and be delivered to N number of clients. Some of these clients are other Java classes in my server-side app, but the main consumer is my javascript-based WebUI.
My current approach thus-far was to define an abstract event base class to encapsulate some common fields, then implement a specific event class for each event.
This has been working fine, except now I need to maintain the event on both the javascript and java side so either side can react to the others events.
I had a thought this morning that I could utilize Thrift (which the project already makes heavy use of) to define the event data structures and auto-generate the classes on either side. This not only handles the tedium of writing the class files, but ensures consistency.
My issue is that since data objects in thrifts are Structs (which can't be extended), I have no way of encapsulating the common fields nor can I pass the events along using a single base class.
The workaround I've come up with thus far is to define a struct inside the thrift IDL to act as a 'base' class, with an optional field for each and every event type that I define. This would still let me have a single class to refer to events generically while also letting me capture the relevant data when spawning events.
Maybe this is just me not being very familiar with thrift, but this feels like a hack. Am I way off, or is this an ok approach? Is there a better way to accomplish this?
Thrift as an serialization and RPC mechanism allows only for one-to-one connections, so that will not really solve the task. But you're not lost.
If you want to do one-to-many, you should use some messaging system. Thrift can be easily combined with messaging systems on various levels. The /contrib folder of the source tree holds a few examples on how to achieve that.
Using a Thrift union as the envelope to hold all you various data structures is a valid solution, because it allows to minimize the serialization and deserialzation code - you only need one pair of functions to deal with always the same Envelope structure (which of course may have different contents).
struct Foo { ... some member fields ... }
struct Bar { ... some member fields ... }
struct Baz { ... some member fields ... }
union Envelope {
1: Foo foo
2: Bar bar
3: Baz baz
}
Related
I have created a class to interact with my database:
class MyDatabase {
connect() { /* ... */ }
}
And the database has two types of modes: admin and client. I would like to have different classes for each mode:
class MyDatabaseAdmin {}
class MyDatabaseClient {}
Both of them will implement the same interface, but with different underline implementations. I would like to know if there is a design pattern to instantiate the parent MyDatabase choosing one over the other. Something like:
const db = new MyDatabase({ mode: 'admin' })
db.connect() // parent calls MyDatabaseAdmin.connect
I don't need a perfect answer, just some direction to what I should search for.
Thanks.
If they have no code in common, then they are really just two separate classes. You probably don't even want the admin code to be present in the browser since it can't be used there anyway.
You could have a single factory function that looks at an admin parameter and instantiates the appropriate database object and returns it, but I don't think I even see why you'd bother with that.
Just have each client instantiate the appropriate DB object. If there's any common code, you can have both implementations inherit from a common base and put the common code in the base class.
Right! I forgot to mention, but there are some common code... the connection and authentication is exactly the same, for example. Do you happen to know any design pattern that would perfect fit for this use case? Should I research about Factories?
I think a common base class with inheritance solves the problem here. It gives you a natural place to put the common code without having to include server-side code in the client implementation. The browser implementation and the server implementation would each be a subclass that are present only on their respective platforms. The common base class would be present and used in both places.
You just have the client instantiate the appropriate leaf class and the shared code lives in the base class. If you want to hide the actual class constructors, you can use a factory function (it's just a simple function that looks at conditions and makes an appropriate object for you and returns it), but I'm not sure there's any compelling reason to use a factory function here. You would only include the appropriate leaf class on the platform for which it is intended so there's no place where you might use one or the other in the same code.
would you consider having only 'users'? then each user could have a 'role' that would be either 'user' or 'admin'. So based on that 'role' you will define the privileges for each user. I find this solution easier for this kind of stuff but let me know if it does not match your case.
I know that in sequence diagram I need to represent just classes between two actors but in my application I have just one class. This class is a ser.java that is going to write data in a file.txt then a php file read from this file and display the information on an interface.html using javascript file, interface.html is the interface of my app. Here the operator is not in direct relation with my class ser.java. and the ser.java is not also in direct relation with my app there is a files bet them So, how can I represent the sequence diagram?
Thank you.
Your terminology isn't quite right, and maybe this is the cause for your confusion.
A sequence diagram doesn't show classes between actors, but the message flow between objects which may have a data type that may be a class. So you'll probably have one object of your class Ser and other objects representing your txt, php, and html files.
As files are passive objects that don't initiate any functionality, I assume that your message flow will always start at the object that is an instance of Ser. Therefore, I don't think your statement that "php file read from this file" is quite precise. Who initiates the reading? In your description, only the Ser instance is able to do such a thing.
You are also talking about your app being different from Ser. So do you have an app object that must be an instance of another class? This could also be represented in your diagram.
There is no strict rule about what to include in a sequence diagram. UML is a language, and, like every language, it allows you to express your thoughts. So if you find some object relevant enough to tell about the messages it sends and receives, include it. You'll need to stop somewhere, as otherwise you'll end up describing your processor and each storage cell. In general, people tend to describe objects of classes they have written or they are directly calling from their own classes.
This question is regarding a best practice for structuring data objects using JS Modules on the server for consumption by another module.
We have many modules for a web application, like login view, form handlers, that contain disparate fragments of data, like user state, application state, etc. which we need to be send to an analytics suite that requires a specific object format. Where should we map the data? (Pick things we want to send, rename keys, delete unwanted values.)
In each module. E.g.: Login knows about analytics and its formatting
requirements.
In an analytics module. Now analytics has to know
about each and every module's source format.
In separate [module]-analytics modules. Then we'll have dozen of files which don't have much context to debug and understand.
My team is split on what is the right design. I'm curious if there is some authoritative voice on the subject that can help us settle this.
Thanks in advance!
For example,
var objectForAnalytics = {
logged_in: user.get('isLoggedIn'),
app_context: application.get('environment')
};
analytics.send(objectForAnalytics);
This short sample script uses functions from 3 modules. Where should it exist in a well-organized app?
JS doesn't do marshaling, in the traditional sense.
Since the language encourages duck typing and runs all loaded modules in a single VM, each module can simply pass the data and let a consumer choose the fields that interest them.
Marshaling has two primary purposes, historically:
Delivering another module the data that it expects, since C-style structures and objects do not support extra data (usually).
Transferring data between two languages or modules built on two compilers, which may be using different memory layouts, calling conventions, or ABIs.
JavaScript solves the second problem using JSON, but the first is inherently solved with dictionary-style objects. Passing an object with 1000 keys is just as fast as an object with 2, so you can (and often are encouraged) to simply give the consumer what you have and allow them to decide what they need.
This is further reinforced in languages like Typescript, where the contract on a parameter type is simply a minimum set of requires. TS allows you to pass an object that exceeds those requires (by having other fields), instead only verifying that you are aware of what the consumer states they require in their contract and have met that.
When you do need to transform an object, perhaps because two library use the same data with different keys, creating a new object with shallow references is pretty easy:
let foo = {
bar: old.baz,
baz: old.bin
};
This does not change or copy the underlying data, so any changes to the original (or the copy) will propagate to the other. This does not include primitive values, which are immutable and so will not propagate.
I'm very interested in using the new EntityErrorsException that came with today's release. But the way my colleague implemented the server-side logic might be an issue.
In the webAPI controller, we use our own contextProvider, which inherits from breeze's EFContextProvider. See code below:
public class SepaContextProvider : EFContextProvider<CompanyName.BLL.BLDirectDebitContext>
{
public MyContextProvider() : base() { }
}
As you can see, the generic parameter is a BLDirectDebitContext, which inherits from a DirectDebitContext class defined in the data-access layer:
public class DirectDebitContext : DbContext{
}
This way, the entities are validated in the BLDirectDebitContext class by overriding ValidateEntity() so that if this code is called from a desktop application (that don't use webAPI or even breeze), the validation logic does not have to be re-written.
Ideally, we could create EFEntityError objects here and throw a EntityErrorsException. But that would mean referencing breeze.webapi dll in our business layer, which does not sound so good considering the number of dependencies.
Would it not make more sense to split the breeze.webapi dll into different dll's ? Or is it our approach that does not make any sense ?
We are planning to refactor Breeze.WebApi into at least two or three dll's in the near future. (Sorry no exact date yet). One that includes the core .NET generic code ( with substantially fewer dependencies) and the other that is Entity Framework specific. We plan to release an NHibernate specific dll at the same time, in parallel to the Entity Framework version.
This will, of course, be a breaking change which is why we are trying to get everything organized properly so that we don't have to do this again. Ideally, the conversion from the current structure to the new one will be fairly easy for any Breeze consumers.
On a slightly related issue, did you notice that you can also use standard .NET DataAnnotation Validation attributes as well as the EntityErrorsException. The two mechanisms result in exactly the same client side experience.
I've started to wrap my functions inside of Objects, e.g.:
var Search = {
carSearch: function(color) {
},
peopleSearch: function(name) {
},
...
}
This helps a lot with readability, but I continue to have issues with reusabilty. To be more specific, the difficulty is in two areas:
Receiving parameters. A lot of times I will have a search screen with multiple input fields and a button that calls the javascript search function. I have to either put a bunch of code in the onclick of the button to retrieve and then martial the values from the input fields into the function call, or I have to hardcode the HTML input field names/IDs so that I can subsequently retrieve them with Javascript. The solution I've settled on for this is to pass the field names/IDs into the function, which it then uses to retrieve the values from the input fields. This is simple but really seems improper.
Returning values. The effect of most Javascript calls tends to be one in which some visual on the screen changes directly, or as a result of another action performed in the call. Reusability is toast when I put these screen-altering effects at the end of a function. For example, after a search is completed I need to display the results on the screen.
How do others handle these issues? Putting my thinking cap on leads me to believe that I need to have an page-specific layer of Javascript between each use in my application and the generic methods I create which are to be used application-wide. Using the previous example, I would have a search button whose onclick calls a myPageSpecificSearchFunction, in which the search field IDs/names are hardcoded, which marshals the parameters and calls the generic search function. The generic function would return data/objects/variables only, and would not directly read from or make any changes to the DOM. The page-specific search function would then receive this data back and alter the DOM appropriately.
Am I on the right path or is there a better pattern to handle the reuse of Javascript objects/methods?
Basic Pattern
In terms of your basic pattern, can I suggest modifying your structure to use the module pattern and named functions:
var Search = (function(){
var pubs = {};
pubs.carSearch = carSearch;
function carSearch(color) {
}
pubs.peopleSearch = peopleSearch;
function peopleSearch(name) {
}
return pubs;
})();
Yes, that looks more complicated, but that's partially because there's no helper function involved. Note that now, every function has a name (your previous functions were anonymous; the properties they were bound to had names, but the functions didn't, which has implications in terms of the display of the call stack in debuggers and such). Using the module pattern also gives you the ability to have completely private functions that only the functions within your Search object can access. (Just declare the functions within the big anonymous function and don't add them to pubs.) More on my rationale for that (with advantages and disadvantages, and why you can't combine the function declaration and property assignment) here.
Retrieving Parameters
One of the functions I really, really like from Prototype is the Form#serialize function, which walks through the form elements and builds a plain object with a property for each field based on the field's name. (Prototype's current – 1.6.1 – implementation has an issue where it doesn't preserve the order of the fields, but it's surprising how rarely that's a problem.) It sounds like you would be well-served by such a thing and they're not hard to build; then your business logic is dealing with objects with properties named according to what they're related to, and has no knowledge of the actual form itself.
Returning Values / Mixing UI and Logic
I tend to think of applications as objects and the connections and interactions between them. So I tend to create:
Objects representing the business model and such, irrespective of interface (although, of course, the business model is almost certainly partially driven by the interface). Those objects are defined in one place, but used both client- and server-side (yes, I use JavaScript server-side), and designed with serialization (via JSON, in my case) in mind so I can send them back and forth easily.
Objects server-side that know how to use those to update the underlying store (since I tend to work on projects with an underlying store), and
Objects client-side that know how to use that information to render to the UI.
(I know, hardly original!) I try to keep the store and rendering objects generic so they mostly work by looking at the public properties of the business objects (which is pretty much all of the properties; I don't use the patterns like Crockford's that let you really hide data, I find them too expensive). Pragmatism means sometimes the store or rendering objects just have to know what they're dealing with, specifically, but I do try to keep things generic where I can.
I started out using the module pattern, but then started doing everything in jQuery plugins. The plugins allow to pass page specific options.
Using jQuery would also let you rethink the way you identify your search terms and find their values. You might consider adding a class to every input, and use that class to avoid specifically naming each input.
Javascript is ridiculously flexible which means that your design is especially important as you can do things in many different ways. This is what probably makes Javascript feel less like lending itself to re-usability.
There are a few different notations for declaring your objects (functions/classes) and then namespacing them. It's important to understand these differences. As mentioned in a comment on here 'namespacing is a breeze' - and is a good place to start.
I wouldn't be able to go far enough in this reply and would only be paraphrasing, so I recommend buying these books:
Pro JavaScript Design Patterns
Pro Javascript techniques